-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
43 lines (38 loc) · 1.05 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
package removelinkedlistelements;
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
/**
* Runtime: 1 ms, faster than 93.14% of Java online submissions for Remove Linked List Elements.
* Memory Usage: 46.5 MB, less than 24.25% of Java online submissions for Remove Linked List Elements.
*/
private ListNode removeElements(ListNode head, int val) {
ListNode current = head, prev = head;
while (current != null) {
if (current.val == val) {
// check if first node in LL
if (current == head) {
head = current.next;
prev = current.next;
} else {
prev.next = current.next;
}
} else {
prev = current;
}
current = current.next;
}
return head;
}
}