Delete Node in a Linked List
The task here is to delete a node from a singly linked list when you have access to only that node (and not the head of the list). Since you cannot access the previous node, you cannot simply change its next
pointer. Here’s how you can delete the node without accessing the previous one:
- Copy the Value: Copy the value from the next node to the current node.
- Update the Link: Make the current node’s
next
pointer point to the next node’snext
node. - Delete Next Node: This way, the value from the next node is effectively “moved” to the current node, and the next node is skipped over.
Here is the code that implements this logic:
|
|
Explanation:
node.val = node.next.val
copies the value from the next node to the current node.node.next = node.next.next
makes the current node’snext
pointer skip the next node, effectively deleting it.
This approach works in constant time O(1) and does not require any additional space. It takes advantage of the fact that we don’t need to actually remove the node from memory; we only need to ensure that its value does not exist in the linked list and that the linked list’s order is maintained.
|
|