203.Remove Linked List Elements

Solution 1: accepted 2ms

Should be the most straight forward solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode result = dummy;
while (dummy.next != null) {
if (dummy.next.val == val) {
dummy.next = dummy.next.next;
} else {
dummy = dummy.next;
}
}
return result.next;
}
}