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
class Solution { public ListNode removeElements(ListNode head, int val) { while(head != null && head.val == val) head = head.next; ListNode cur = head; while(cur != null && cur.next != null){ if(cur.next.val == val) cur.next = cur.next.next; else cur = cur.next; } return head; } }
iterative way
First, we shift a head of a list while its' value equals to val.
Then, we iterate through the nodes of the list checking if the next node's value equals to val and removing it if needed.
One thing need to know is we only do cur = cur.next if cur.next.val != val. Say we have [1, 2, 2, 1] and val = 2, if we always do cur = cur.next, we will miss the second val==2 node.