237. Delete Node in a Linked List #113
-
Topics: There is a singly-linked list You are given the node to be deleted All the values of the linked list are unique, and it is guaranteed that the given node Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:
Custom testing:
Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to effectively delete the given node by modifying the list in place. The key idea here is to copy the value from the next node into the current node and then skip over the next node. Steps to solve the problem:
Let's implement this solution in PHP: 237. Delete Node in a Linked List <?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;
}
}
function deleteNode($node) {
// Step 1: Copy the value from the next node into the current node
$node->val = $node->next->val;
// Step 2: Point the current node's next to the next node's next
$node->next = $node->next->next;
}
// Example usage:
// Create the linked list: 4 -> 5 -> 1 -> 9
$head = new ListNode(4);
$head->next = new ListNode(5);
$head->next->next = new ListNode(1);
$head->next->next->next = new ListNode(9);
// Assuming we want to delete node with value 5
$nodeToDelete = $head->next;
// Call the function to delete the node
deleteNode($nodeToDelete);
// Output the list to see the result: 4 -> 1 -> 9
$current = $head;
while ($current !== null) {
echo $current->val . " ";
$current = $current->next;
}
?> Explanation:
Example:For the input linked list
Output:
This solution efficiently deletes the node in the linked list without the need to traverse the list from the head, adhering to the problem's constraints. |
Beta Was this translation helpful? Give feedback.
We need to effectively delete the given node by modifying the list in place. The key idea here is to copy the value from the next node into the current node and then skip over the next node.
Steps to solve the problem:
next
pointer of the given node to skip over the next node (effectively removing the next node from the list).Let's implement this solution in PHP: 237. Delete Node in a Linked List