Delete Nodes From Linked List Present in Array
Delete Nodes From Linked List Present in Array
You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums.
Example 1:
Input: nums = [1,2,3], head = [1,2,3,4,5]
Output: [4,5]
Explanation:
Example 2:
Input: nums = [1], head = [1,2,1,2,1,2]
Output: [2,2,2]
/**
* Definition for singly-linked list.
* public 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 {
public ListNode modifiedList(int[] nums, ListNode head) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums) {
set.add(num); // Store nums in HashSet for fast lookup
}
// Step 1: Handle head removal
while (head != null && set.contains(head.val)) {
head = head.next; // Move head to next valid node
}
// Step 2: Traverse the linked list and remove unwanted nodes
ListNode current = head;
while (current != null && current.next != null) {
if (set.contains(current.next.val)) {
current.next = current.next.next; // Skip the node
} else {
current = current.next; // Move forward
}
}
return head; // Return modified list
}
}
Comments
Post a Comment