Delete Node In A Linked List
To solve this coding challenge, you need to manipulate a singly-linked list such that a given node (excluding the last node) is effectively "deleted" from the list. A clever trick here involves copying the value from the next node into the node to be "deleted," then unlinking the next node.
Explanation
In a singly linked list, each node contains two parts: a value and a reference (or pointer) to the next node in the sequence. The challenge specifies that you will be given access only to the node to be deleted and not the head of the list. This is a crucial detail that influences the approach.Detailed Steps in Pseudocode:
Step-by-Step Explanation
-
Understand Node Structure:
Each node in a singly-linked list typically contains a value and a reference to the next node. Let's call the node to be deleted
.
node -
Copy Next Nodeβs Value:
Take the value from the node that comes immediately after
(i.e.,
node) and copy it intonode.next. This effectively overwrites the current node's value with the value of the next node.node -
Skip the Next Node:
Adjust the
pointer of
nextto skip over the immediate next node. This can be done by settingnodetonode.next. This step essentially removes the next node from the list by bypassing it in the sequence.node.next.next -
Completion:
After these operations, the
will contain the value that was in
node, and the list will effectively skip over the originalnode.next.node.next - Step 1: Copy the Value
-
Access the value of the node that comes immediately after the current node (i.e.,
).
node.next.value - Overwrite the current node's value with this value. This makes the current node act as if it is the next node.
- Step 2: Adjust the Next Pointer
-
Change the
pointer of the current node to point to the node after the next node (i.e.,
next).node.next.next - This step effectively removes the "next" node from the linked list sequence because no nodes will be directly pointing to it anymore.
- Input: head = [4,5,1,9], node = 5
- The node to be deleted has the value 5.
-
List:
4 -> 5 -> 1 -> 9
Step-by-Step Execution:
- Copy the value from the next node:
-
is
node.value, and5isnode.next.value.1 -
After copying,
becomes
node.value.1
List state:
- Adjust the pointer:
-
is currently pointing to the node with value
node.next.1 -
Change
to point to
node.next, which is the node with valuenode.next.next.9
List state after deletion:
Pseudocode with Comments:
# Define the function which takes the node to be deleted
function deleteNode(node):
# Step 1: Copy the value from the next node into the current node
node.value = node.next.value
# Step 2: Bypass the next node by pointing this node's next to next node's next
node.next = node.next.next
Detailed Steps in Pseudocode
Example Walkthrough
Let's illustrate these steps using an example from the problem description:Example 1:
4 -> 1 -> 1 -> 9
4 -> 1 -> 9