Poison

203. Remove Linked List Elements

递归
1
2
3
4
5
6
7
8
9
10
class Solution {
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;
}
}
迭代
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 dummyHead = new ListNode(-1, head);
ListNode curr = dummyHead;
while (curr.next != null) {
if (curr.next.val == val) {
curr.next = curr.next.next;
} else {
curr = curr.next;
}
}

return dummyHead.next;
}
}
Reference

203. Remove Linked List Elements