-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL203.java
More file actions
37 lines (36 loc) · 1.08 KB
/
L203.java
File metadata and controls
37 lines (36 loc) · 1.08 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
public class L203 {
class Solution {
/**
* 203. Remove Linked List Elements https://leetcode.com/problems/remove-linked-list-elements
*
* @param head
* Head of the list
* @param val
* Value to be removed
* @return Head of the new list
* @timeComplexity O(n)
* @spaceComplexity O(1)
*/
public ListNode removeElements(ListNode head, int val) {
// Remove all the val nodes from the beginning
while (head != null && head.val == val) {
head = head.next;
}
// Check if we are at the end of list already
if (head == null) {
return head;
}
ListNode ptr = head;
ListNode prev = null;
while (ptr != null) {
if (ptr.val == val) {
prev.next = ptr.next;
} else {
prev = ptr;
}
ptr = ptr.next;
}
return head;
}
}
}