algoritmauzmanı
TREN
3.2Doubly Linked List
Lesson 3.2.5

Deleting a node

Deleting a means taking it out from between its two neighbours and linking the neighbours to each other. In a doubly linked list a node carries the address of the node in front of it. That makes deletion easier than deleting from the middle of a singly linked list: there is no need to search for the previous node.

What you will learn
  • Which two assignments link the two neighbours of the deleted node to each other
  • How the first node, the last node and a one-node list are handled
  • Why removing a node you already hold is
7 minTime O(n)Memory O(1)C · Java · Python

1Idea

The code first finds the node to delete: it starts at and moves forward pos times. If the list is empty or the position is outside the list, target becomes NULL and the function returns without changing anything.

Taking the node out of the list is two assignments. The field of the node in front is pointed at the node behind: target->prev->next = target->next. The field of the node behind is pointed at the node in front: target->next->prev = target->prev. Now the two neighbours point to each other and no link leads to the target any more.

At the ends one of the neighbours is missing. When the first node is deleted there is nothing in front of it; instead is moved to the node behind. When the last node is deleted there is nothing behind it and the second assignment is skipped. In a one-node list both happen and becomes NULL. In C the memory is finally returned with ; in Java and Python the garbage collector does that.

If you already hold the node to delete (for example, a search returned it), the loop is not needed: the remaining lines take constant time. In a singly linked list holding the node is not enough, because finding the previous node means walking from the start. In a doubly linked list the previous node is in target->prev.

2Step by step

The drawing deletes the node at position 2 (holding 3) from a list holding 12, 7, 3 and 9. Blue arrows are prev links. The node being deleted is drawn one row lower so that the links stay visible. At each step the matching line of code lights up.

NULLNULL12?0x1a407?0x1a903?0x1b209?0x2c10headtarget
  1. Start. points to 12. We will delete the node at position 2, which holds 3.
  2. target starts at , that is, at 12.
  3. First round: target moves to 7.
  4. Second round: target moves to 3. The loop ends. The node is not NULL, so it will be deleted.
  5. There is a node in front of 3 (7). The field of 7 is pointed at the node behind 3, which is 9. The forward path now skips 3.
  6. There is a node behind 3 (9). The field of 9 is pointed at the node in front of 3, which is 7. The backward path skips 3 too.
  7. No link in the list leads to 3 any more. In C its memory is returned with .
  8. Result: 12 ⇄ 7 ⇄ 9. Only two links changed.

struct Node {    int data;    struct Node* prev;    struct Node* next;}; void deleteAt(struct Node** head, int pos) {    if (pos < 0) return;    struct Node* target = *head;    for (int i = 0; i < pos && target != NULL; i++)        target = target->next;    if (target == NULL) return;     // empty list or invalid position    if (target->prev != NULL)        target->prev->next = target->next;    else        *head = target->next;         // deleting the first node    if (target->next != NULL)        target->next->prev = target->prev;    free(target);}
class Node {    int data;    Node prev, next;    Node(int data) { this.data = data; }} Node deleteAt(Node head, int pos) {    if (pos < 0) return head;    Node target = head;    for (int i = 0; i < pos && target != null; i++)        target = target.next;    if (target == null) return head;  // empty list or invalid position    if (target.prev != null)        target.prev.next = target.next;    else        head = target.next;            // deleting the first node    if (target.next != null)        target.next.prev = target.prev;    return head;  // the garbage collector frees the removed node}
class Node:    def __init__(self, data):        self.data = data        self.prev = None        self.next = None def delete_at(head, pos):    if pos < 0:        return head    target = head    for _ in range(pos):        if target is None:            return head  # invalid position        target = target.next    if target is None:        return head  # empty list or invalid position    if target.prev is not None:        target.prev.next = target.next    else:        head = target.next  # deleting the first node    if target.next is not None:        target.next.prev = target.prev    return head  # the garbage collector frees the removed node

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Finding the node at the position takes up to n steps in the worst case. Taking it out takes constant time.

Memory
O(1)

No space is needed apart from a single pointer.

If you hold the node, deletion is . In a singly linked list deleting the same node requires finding the previous node, which is .

4Common mistake

The most common mistake is writing the two assignments directly, without thinking about the ends:

target->prev->next = target->next;target->next->prev = target->prev;free(target);

This is right for a node in the middle. But for the first node target->prev is NULL and the first line writes through NULL; for the last node the second line does the same. The program crashes. Updating when the first node is deleted is forgotten as well: keeps pointing to freed memory. Every assignment needs a NULL check in front of it.

5Try it

On a one-node list, which lines run when deleteAt(&head, 0) is called?

Show the answer

The answer is B. The single node's and fields are NULL. The first if is false and gets target->next, which is NULL. The second if is false too and its assignment is skipped. Then the node is freed and the list is empty.

If you hold the address of the node to delete, why is deletion O(1) in a doubly linked list?

Show the answer

The answer is B. Deleting requires changing the field of the previous node. In a singly linked list you walk from the start to find it. In a doubly linked list the field gives it directly; what is left is a few assignments.

Lessons you mark show up in the curriculum. This is kept on this device only.