3217. Delete Nodes From Linked List Present in Array #493
Answered
by
basharul-siddike
mah-shamim
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
basharul-siddike
Sep 7, 2024
Replies: 1 comment 2 replies
-
We need to traverse through the linked list and remove any nodes that have a value present in the array Approach:
Steps:
Let's implement this solution in PHP: 3217. Delete Nodes From Linked List Present in Array <?php
// Definition for a singly-linked list node.
class ListNode {
public $val = 0;
public $next = null;
function __construct($val = 0, $next = null) {
$this->val = $val;
$this->next = $next;
}
}
class Solution {
// Main function to remove nodes present in the array nums
function removeElements($head, $nums) {
// Convert nums array to a hash set for O(1) lookups
$numSet = array_flip($nums);
// Create a dummy node to handle edge cases (e.g. removing the head)
$dummy = new ListNode(0);
$dummy->next = $head;
// Initialize pointers
$prev = $dummy;
$current = $head;
// Traverse the linked list
while ($current !== null) {
// If the current node's value exists in numSet, remove it
if (isset($numSet[$current->val])) {
$prev->next = $current->next; // Skip the current node
} else {
$prev = $current; // Move prev pointer forward
}
$current = $current->next; // Move current pointer forward
}
// Return the modified list starting from the dummy's next node
return $dummy->next;
}
}
// Example usage:
// Linked List: 1 -> 2 -> 3 -> 4 -> 5
$head = new ListNode(1);
$head->next = new ListNode(2);
$head->next->next = new ListNode(3);
$head->next->next->next = new ListNode(4);
$head->next->next->next->next = new ListNode(5);
// Array nums: [1, 2, 3]
$nums = [1, 2, 3];
$solution = new Solution();
$result = $solution->removeElements($head, $nums);
// Function to print the linked list
function printList($node) {
while ($node !== null) {
echo $node->val . " ";
$node = $node->next;
}
}
// Print the resulting linked list
printList($result); // Output: 4 5
?> Explanation:
Example Walkthrough:For input
The resulting linked list is |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
mah-shamim
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We need to traverse through the linked list and remove any nodes that have a value present in the array
nums
.Approach:
nums
needs to be efficient, we will convertnums
into a hash set. This allows O(1) lookup for each value.nums
array.Steps:
nums
to a hash set for O(1) lookup.