Removing given node in Doubly Linked List

Pattern: Doubly and circular lists

medium

You are handed the node itself, which is never the head. Its prev and next are both reachable, so link them to each other and the node is gone.

The problem

You are given one node of a doubly linked list, which is guaranteed not to be the head. Remove it from the list; the function returns nothing. For example, in 1 ⇄ 2 ⇄ 3, removing the node 2 leaves 1 ⇄ 3.

The function name deleteGivenNode matches the takeUforward practice page. Use the link above for the exact statement and limits. In this guide's code the node type is DNode. The tests hand the function the node at a given index and print the list from the head afterwards, checking every prev link.

Think first

  • In a singly linked list, you had to copy the next value. Why is that not needed here?
  • Which two pointers change?
  • Why does "never the head" make the code simpler?

Hints

    Brute force, and why it fails

    There is nothing simpler: two pointer changes, O(1).

    The key insight

    This is the payoff of prev: deleting a node needs no walk and no value tricks, only its two neighbours.

    Dry run

    10 
    21 
    32 

    The list is 1 ⇄ 2 ⇄ 3, and you are handed the node 2.

    Step 1 of 4

    The plan

    node.prev.next = node.next
    if node.next is not null: node.next.prev = node.prev
    

    Complexity

    Time
    O(1)
    Space
    O(1)

    Two assignments.

    Edge cases

    • The node is the tail: only prev.next changes.
    • The node is second: the head's next changes.
    • Two nodes, removing the second: the head is left alone.
    I've built my logic, show the code

    Java

    class Solution {
        public void deleteGivenNode(DNode node) {
            node.prev.next = node.next;             // the node is never the head, so prev exists
            if (node.next != null) node.next.prev = node.prev;
        }
    }

    C++

    class Solution {
    public:
        void deleteGivenNode(DNode* node) {
            node->prev->next = node->next;          // the node is never the head, so prev exists
            if (node->next != NULL) node->next->prev = node->prev;
        }
    };

    Python

    from lib import DNode
    
    class Solution:
        def deleteGivenNode(self, node: DNode) -> None:
            node.prev.next = node.next              # the node is never the head, so prev exists
            if node.next is not None:
                node.next.prev = node.prev

    Common mistakes

    • Forgetting the prev update on the next node.
    • Reading node.next.prev when node.next is null.
    • Copying values as in the singly linked trick, which is not needed.

    Similar problems