algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.9

Deleting from the middle

Deleting from the middle is the general form of deleting from the head and from the end: it removes the at any position in the list. Positions start at 0. The way to take a node out is to find the node before it and make the link skip over the node being deleted.

What you will learn
  • Why the node before the target is reached in pos - 1 steps
  • How the link skips over the target node, and when the node is given back
  • How position 0 and invalid positions are handled
6 minTime O(n)Memory O(1)C · Java · Python

1Idea

Taking a node out of the list means pointing the field of the node before it at the node after it. A singly linked list cannot go backwards, so we start from and move pos - 1 steps. temp stops on that node; temp->next is the node to delete.

Then temp->next = target->next makes the link skip over the target. The list no longer reaches it. In C we give it back with through the target pointer; without that pointer the node's address would be lost and we would have a .

At position 0 there is no previous node; the operation is deleting from the head and changes. If the position is negative, or equal to or greater than the length of the list, there is no node to delete and the list stays unchanged.

Deleting by value

Sometimes you get a value instead of a position: "delete 7". The structure is the same; only the loop condition changes. temp moves forward until the next node holds the value you are looking for. If the first node holds it, you delete from the head as before.

while (temp->next != NULL && temp->next->data != value)    temp = temp->next;

2Step by step

The drawing deletes the node at position 2 (3) from a list holding 12, 7, 3 and 9. Positions start at 0. At each step the matching line of code lights up.

NULL12?0x1a407?0x1a903?0x1b209?0x1c60headtemptarget
  1. Start. points to 12. The node at position 2 is 3.
  2. The position is valid and not 0. temp starts at the first node.
  3. The loop runs pos - 1 times, that is, once. temp stops at 7: the node before the target.
  4. temp->next is not , so there is a node at position 2. Its address is kept in target.
  5. temp->next = target->next: the field of 7 now points to 9. 3 has left the list but still points to 9.
  6. In C the memory of 3 is returned with . Java and Python have no such line; the garbage collector reclaims the node.
  7. Result: 12 → 7 → 9. did not change.

struct Node {    int data;    struct Node* next;}; void deleteAt(struct Node** head, int pos) {    if (*head == NULL || pos < 0) return;    // invalid    struct Node* temp = *head;    if (pos == 0) {                          // delete the head        *head = temp->next;        free(temp);        return;    }    for (int i = 0; i < pos - 1 && temp->next != NULL; i++)        temp = temp->next;    if (temp->next == NULL) return;          // position past the end    struct Node* target = temp->next;    temp->next = target->next;    free(target);}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node deleteAt(Node head, int pos) {    if (head == null || pos < 0) return head;  // invalid    if (pos == 0) return head.next;             // delete the head    Node temp = head;    for (int i = 0; i < pos - 1 && temp.next != null; i++)        temp = temp.next;    if (temp.next == null) return head;         // position past the end    temp.next = temp.next.next;    return head;}
class Node:    def __init__(self, data):        self.data = data        self.next = None def delete_at(head, pos):    if head is None or pos < 0:  # invalid        return head    if pos == 0:  # delete the head        return head.next    temp = head    i = 0    while i < pos - 1 and temp.next is not None:        temp = temp.next        i += 1    if temp.next is None:  # position past the end        return head    temp.next = temp.next.next    return head

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

3Complexity

Time
O(n)

Reaching the previous node passes over at most n − 1 nodes. Position 0 is .

Memory
O(1)

Two helper pointers and a counter are used.

Changing the link is a single assignment; all the time goes into finding the node. With the previous node already in hand, deletion would take constant time. Inserting at a position works the same way.

4Common mistake

The most common mistake is running the loop one step too far:

for (int i = 0; i < pos; i++)  // should be pos - 1    temp = temp->next;

This loop takes temp to the target node itself. A singly linked list cannot step back to the node before it; the following temp->next = temp->next->next line then deletes the next node instead. For the last node it also reads through . When deleting, always stop one node before the target.

5Try it

Why is there a separate branch for position 0?

Show the answer

The answer is B. At other positions the field of the previous node changes. The first node has no node before it, so what changes is . That is why the C function takes struct Node**.

What happens if deleteAt(head, 4) is called on a four-node list?

Show the answer

The answer is B. The positions are 0, 1, 2 and 3. The loop takes temp to the last node, and since temp->next is the function returns without changing anything. To delete the last node, pass position 3 or use deleting from the end.

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