203 Remove Linked List Elements

1. Question

Remove all elements from a linked list of integers that have valueval.
Example Given:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,val= 6 Return:1 --> 2 --> 3 --> 4 --> 5

2. Implementation

1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
public ListNode removeElements(ListNode head, int val) {
11
ListNode dummy = new ListNode(0);
12
dummy.next = head;
13
ListNode preNode = dummy, curNode = head;
14
15
while (curNode != null) {
16
if (curNode.val == val) {
17
preNode.next = curNode.next;
18
}
19
else {
20
preNode = preNode.next;
21
}
22
curNode = curNode.next;
23
}
24
return dummy.next;
25
}
26
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(1)