-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode_3217.java
34 lines (29 loc) · 1.07 KB
/
Leetcode_3217.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
class Solution {
public ListNode modifiedList(int[] nums, ListNode head) {
// Create a HashSet for efficient lookup of values in nums
Set<Integer> valuesToRemove = new HashSet<>();
for (int num : nums) {
valuesToRemove.add(num);
}
// Handle the case where the head node needs to be removed
while (head != null && valuesToRemove.contains(head.val)) {
head = head.next;
}
// If the list is empty after removing head nodes, return null
if (head == null) {
return null;
}
// Iterate through the list, removing nodes with values in the set
ListNode current = head;
while (current.next != null) {
if (valuesToRemove.contains(current.next.val)) {
// Skip the next node by updating the pointer
current.next = current.next.next;
} else {
// Move to the next node
current = current.next;
}
}
return head;
}
}