PadhaikoAll subjects

Past exam question: 2077 Chaitra (Regular), Q9

Data Structure and Algorithms · 6 marks

Open in the Padhaiko app

Topic: Linked List

Question

Explain with example how node in a singly linked list can be deleted?

Solution

Cases for Deleting the -th Node (1-Based Position):

  1. Empty List (head == NULL): Report underflow and return.
  2. Delete First Node (n == 1): Save temp = head, advance head = head->next, and free(temp).
  3. Delete Node at Position :
    • Walk pointer prev from head for steps so prev points to node .
    • If prev == NULL or prev->next == NULL, position exceeds list length.
    • Otherwise, let target = prev->next, set prev->next = target->next, and free(target).

Algorithm and Example Trace:

Node *deleteNth(Node *head, int n) {
    if (head == NULL || n < 1) return head;
    if (n == 1) {
        Node *temp = head;
        head = head->next;
        free(temp);
        return head;
    }
    Node *prev = head;
    for (int i = 1; i < n - 1 && prev != NULL; i++)
        prev = prev->next;
    if (prev == NULL || prev->next == NULL) return head;
    Node *target = prev->next;
    prev->next = target->next;
    free(target);
    return head;
}

Example: Given 10 -> 20 -> 30 -> 40 -> NULL, delete the node (30):

Answer:

To delete the -th node, handle n == 1 by advancing head = head->next; for , advance prev to position , relink prev->next = prev->next->next, and free the detached node. Deleting the 3rd node from 10 -> 20 -> 30 -> 40 yields 10 -> 20 -> 40.

All past exam questions for Data Structure and Algorithms