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
node
node.next
node
-
Skip the Next Node:
Adjust the
next
node
node.next
node.next.next
-
Completion:
After these operations, the
node
node.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
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:
-
node.value
5
node.next.value
1
-
After copying,
node.value
1
List state:
- Adjust the pointer:
-
node.next
1
-
Change
node.next
node.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