203.remove linked list elements

Question

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

Example:

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

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public ListNode removeElements(ListNode head, int val) {
while(head!=null&&head.val==val) //only one element and want to remove it
head = head.next;
ListNode temp = head;
while(head!=null&&head.next!=null){
if(head.next.val==val)
head.next = head.next.next;
else
head = head.next;
}
return temp;// notice some edge condition: [1,1] remove 1
}
}

Some edge condition:

[] -remove-> [] null

[1,1] –remove 1–> []

[1] –remove 1–>[]

Recursive method

1
2
3
4
5
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}