algoritmauzmanı
TREN
3.3Circular Linked List
Lesson 3.3.3

Deleting a node

Deleting from the middle of a singly linked list meant finding the node before the one to delete and skipping over it. The same idea holds in a , but the head also has a node before it: the last node. In this lesson we delete the first node holding a given value and handle all four cases in one function.

What you will learn
  • How the empty list, single node, head node and middle node cases are told apart
  • Why the last node's next field must be updated when the head is deleted
  • Why deletion is O(n) and how the node's memory is given back
7 minTime O(n)Memory O(1)C · Java · Python

1Idea

The function takes a value and deletes the first node that holds it. To take a node out of the ring, the field of the node before it must be moved to the node after it. So along with temp we carry a prev that stays one step behind.

The trick is where prev starts. The node before is the last node, so prev is first moved to the last node. Then the same line also works when the head is deleted: the last node is pointed at the node after the deleted head.

The cases are told apart like this:

  • The list is empty: there is nothing to do and the function returns at once.
  • A single node points to itself and holds the value: the node is deleted and head becomes NULL.
  • The head is deleted: the last node's next is moved to the second node and head moves to the second node.
  • Another node is deleted: prev->next = temp->next is enough and head does not change.
  • The value is not in the list: the loop goes once round, returns to head and the list stays as it was.

In C the memory of the removed node is given back with . In Java and Python the memory is collected on its own once no link reaches the node.

2Step by step

The drawing deletes 12 from a circular list holding 12, 7 and 3. Since the deleted node is the head, the last node's link changes too. At each step the matching line of code lights up.

12?7?3?headprevtemp
  1. Start. points to 12 and the last node, 3, points back to 12. The value to delete is 12.
  2. The list is not empty. prev starts at head and moves on until it reaches the node whose next is head: the last node, 3.
  3. temp starts at head. prev is always one step behind temp; right now 3 is the node before 12.
  4. The value in temp is 12, the one we are looking for. The node does not point to itself, so this is not the single-node case.
  5. The next field of prev is moved to the node after temp. The link coming back from 3 now skips 12 and goes to 7.
  6. The deleted node is the head, so head moves one step on, to 7. No link in the ring reaches 12 any more.
  7. The memory of 12 is given back (). Result: 7 → 3, and 3 points back to 7.

struct Node {    int data;    struct Node* next;}; void deleteValue(struct Node** head, int value) {    if (*head == NULL) return;                  // empty list    struct Node* prev = *head;    while (prev->next != *head)                 // go to the last node        prev = prev->next;    struct Node* temp = *head;    do {        if (temp->data == value) {            if (temp->next == temp) {           // single node                *head = NULL;            } else {                prev->next = temp->next;        // skip the node                if (temp == *head)                    *head = temp->next;         // deleting the head moves head on            }            free(temp);            return;        }        prev = temp;        temp = temp->next;    } while (temp != *head);                    // one full round, value not found}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node deleteValue(Node head, int value) {    if (head == null) return null;              // empty list    Node prev = head;    while (prev.next != head)                   // go to the last node        prev = prev.next;    Node temp = head;    do {        if (temp.data == value) {            if (temp.next == temp)              // single node                return null;            prev.next = temp.next;              // skip the node            return temp == head ? temp.next : head;  // new head if head was deleted        }        prev = temp;        temp = temp.next;    } while (temp != head);    return head;                                // value not found, list unchanged}
class Node:    def __init__(self, data):        self.data = data        self.next = None def delete_value(head, value):    if head is None:                  # empty list        return None    prev = head    while prev.next is not head:      # go to the last node        prev = prev.next    temp = head    while True:        if temp.data == value:            if temp.next is temp:     # single node                return None            prev.next = temp.next     # skip the node            return temp.next if temp is head else head        prev = temp        temp = temp.next        if temp is head:            return head               # value not found, list unchanged

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

3Complexity

Time
O(n)

Moving prev to the last node visits the whole list once; finding the node to delete takes at most one more round.

Memory
O(1)

Only two pointers are used. The deleted node's memory is given back.

Compare: deleting from the head of a singly linked list is . In a circular list the last node changes too when the head is deleted, so the last node has to be found.

4Common mistake

The most common mistake is deleting the head as in a singly linked list:

struct Node* temp = *head;*head = (*head)->next;free(temp);   // last->next still points to the deleted node

The last node's next field points to freed memory; it is a . The next traversal reads that memory after the last node, and the program crashes or prints meaningless values.

5Try it

In a one-node list (the node points to itself), what should head be after that node is deleted?

Show the answer

The answer is A. No node is left, so the list is empty. An empty circular list is a that is . The next field is the node itself, so using it would leave head pointing to freed memory.

Why does the prev pointer in the code start at the last node instead of head?

Show the answer

The answer is A. In a ring, the node before the head is the last node. When prev starts there, the skip line updates the right node even when the head is deleted, and no separate case is needed.

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