203. Remove Linked List Elements (Easy)
https://leetcode.com/problems/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
Solutions
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode preHead = new ListNode(-1);
preHead.next = head;
ListNode p1 = preHead;
ListNode p2 = p1.next;
// a->b->p1->p2
while (p2 != null) {
if (p2.val == val) {
p2 = p2.next;
p1.next = p2;
// do not break since the list may contain duplicates
// break;
} else {
p1 = p2;
p2 = p2.next;
}
}
return preHead.next;
}
}