Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it? Easy 0 attempts
GeeksforGeeks ↗

Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?

Easy Linked List GeeksforGeeks

You are given access to a node in a singly linked list that is to be deleted. You do not have access to the head of the list. The given node is guaranteed not to be the tail node. Write a function to delete the given node by modifying the list in-place. Instead of actually removing the node, copy the next node's value into the current node and then skip the next node.

Example:

Input: list = [4,5,1,9], node = 5
Output: [4,1,9]
Sample Input
Sample Output
Constraints
  • 2 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000
  • The given node is not the tail
Topics

Approach: Copy and Skip

Since we cannot access the previous node, we copy the value of the next node into the current node, then point the current node's next pointer to skip the next node. This effectively deletes the given node from the list.

function givenOnlyAPointerReferenceToANodeToBeDeletedInASinglyLinkedListHowDoYouDeleteIt(node) {
  node.val = node.next.val;
  node.next = node.next.next;
}

Time Complexity: O(1)

Space Complexity: O(1)

Saved in this browser only. Private to you.

JavaScript