-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy path203. Remove Linked List Elements.java
More file actions
executable file
·48 lines (39 loc) · 1.02 KB
/
203. Remove Linked List Elements.java
File metadata and controls
executable file
·48 lines (39 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
E
tags: Linked List
从linked list 里面去掉所有的 target
#### Basics
- 如果match: node.next = head.next;
- 如果不match, node 和 head 一起移动
```
/*
Remove all elements from a linked list of integers that have value val.
Have you met this question in a real interview? Yes
Example
Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5
Tags Expand
Linked List
*/
/*
Thoughts:
While loop through. Maintain a parent, so it can be used to skip current node.
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode node = dummy;
while (head != null) {
if (head.val == val) {
node.next = head.next;
} else {
node = node.next;
}
head = head.next;
}
return dummy.next;
}
}
```