[LeetCode] Problem 203 - Remove Linked List Elements

Remove all elements from a linked list of integers that have value val.

Example

Input: 1->2->6->3->4->5->6, val = 6

Output: 1->2->3->4->5

Code

1
2
3
4
5
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;

while (current.next != null) {
if (current.next.val == val)
current.next = current.next.next;
else
current = current.next;
}

return dummy.next;
}