-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathRemoveLinkedListElements203.java
More file actions
39 lines (35 loc) · 948 Bytes
/
RemoveLinkedListElements203.java
File metadata and controls
39 lines (35 loc) · 948 Bytes
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
/**
* 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
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class RemoveLinkedListElements203 {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
while (p.next != null) {
if (p.next.val == val) {
p.next = p.next.next;
} else {
p = p.next;
}
}
return dummy.next;
}
public ListNode removeElements2(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements2(head.next, val);
return head.val == val ? head.next : head;
}
}