public class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode fakeHead = new ListNode(1);
fakeHead.next = head;
ListNode curr = head, prev = fakeHead;
while (curr != null) {
if (curr.val == val) {
prev.next = curr.next;
} else {
prev = prev.next;
}
curr = curr.next;
}
return fakeHead.next;
}
}
AC Java solution


Here is my code with similar strategy. I did not connect fakeHead with head at the beginning though.
public ListNode removeElements(ListNode head, int val) { ListNode fakeHead = new ListNode(1); ListNode prev = fakeHead; while(head != null) { if(head.val == val) { head = head.next; prev.next = null; // this is necessary!!! } else { prev.next = head; prev = head; head = head.next; } } return fakeHead.next; }

we can do it with only having curr.
public ListNode removeElements(ListNode head, int val) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode cur = dummy; while(cur.next != null) { if(cur.next.val == val) { cur.next = cur.next.next; } else cur = cur.next; } return dummy.next; }

public ListNode removeElements(ListNode head, int val) {
if(null==head) return null; ListNode traverser = head; while(traverser.next!=null){ if(traverser.next.val==val){ traverser.next = traverser.next.next; } else { traverser = traverser.next; } } if(head.val==val) return head.next; return head; }


You actually only need one pointer:
class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(!head) return nullptr; ListNode *dummy = new ListNode(0), *curr = dummy; dummy > next = head; while(curr > next) { if(curr > next > val == val) curr > next = curr > next > next; else curr = curr > next; } return dummy > next; } };



@lx223 Nice solution, I also came out the same idea in the first time.
However, be aware of that, you forgot to set the fakeHead null(or delete it).
So, I'm wondering if this causes possible memory leaking or additionally unused memory over there?