LeetCode – Remove Linked List Elements (Java)
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 Return: 1 --> 2 --> 3 --> 4 --> 5
Java Solution
The key to solve this problem is using a helper node to track the head of the list.
public ListNode removeElements(ListNode head, int val) { ListNode helper = new ListNode(0); helper.next = head; ListNode p = helper; while(p.next != null){ if(p.next.val == val){ ListNode next = p.next; p.next = next.next; }else{ p = p.next; } } return helper.next; } |
<pre><code> String foo = "bar"; </code></pre>
-
N G Sundarasekaran
-
Alik Elzin
-
Hemant Kumar Kushwaha
-
sabari balaji
-
West
-
Anshul
-
Saurabh
-
someone
-
Rakesh Venkatesh
-
cabbar
-
cabbar
-
Vimukthi Weerasiri