-
Notifications
You must be signed in to change notification settings - Fork 57
/
Solution.java
51 lines (50 loc) · 1.36 KB
/
Solution.java
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
49
50
51
/**
* Remove all elements from a linked list of integers that have value val.
*
* Example
* Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
* Return: 1 --> 2 --> 3 --> 4 --> 5
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
boolean isHead = true;
ListNode curr = head, first = head, prev = null, temp = null;
while (curr != null) {
if (isHead) {
if (curr.val == val) {
temp = curr.next;
curr.next = null;
curr = temp;
first = curr;
} else {
isHead = false;
prev = curr;
first = curr;
curr = curr.next;
}
continue;
} else {
if (curr.val == val) {
prev.next = curr.next;
curr.next = null;
curr = prev.next;
} else {
prev = curr;
curr = curr.next;
}
}
}
return first;
}
}