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

Suppose you only have a reference to one particular node inside a singly linked list — not the list's head — and you need to remove that exact node from the list. It's guaranteed that the node you're given is not the last one in the list. Since you can't reach the preceding node, delete it by overwriting its value with the following node's value and then linking past that following node.

Input Format
Implement givenOnlyAPointerReferenceToANodeToBeDeletedInASinglyLinkedListHowDoYouDeleteIt(node). Inputs below show JavaScript function arguments; there is no stdin parsing. Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null. The fixture supplies a list and a zero-based nodeIndex. The editor passes only the selected non-tail node to your function.
Output Format
Return the result described in the statement. Returned list heads are displayed as value arrays; a null head is [].

Sample Input and Output

Example 1 · Run Sample

Input
head = [4,5,1,9]
nodeIndex = 1
Output
[4,1,9]

Example 2

Input
head = [1,2]
nodeIndex = 0
Output
[2]
Constraints
  • 2 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000
  • The given node is not the tail
Test Cases (2)
Case 1
Args: [[4,5,1,9],1] Expected: [4,1,9]
Case 2
Args: [[1,2],0] Expected: [2]
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.

javascript
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