Related Articles

Related Articles

GATE | GATE-IT-2004 | Question 13
  • Last Updated : 30 Nov, 2015

Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-case time complexity of the best known algorithm to delete the node x from the list?
(A) O(n)
(B) O(log2 n)
(C) O(logn)
(D) O(1)


Answer: (D)

Explanation: A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.

Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.

    // Find next node using next pointer
    struct node *temp  = node_ptr->next;

    // Copy data of next node to this node
    node_ptr->data  = temp->data;

    // Unlink next node
    node_ptr->next  = temp->next;

    // Delete next node
    free(temp);

Time complexity of this approach is O(1)

Refer this for implementation.

Note that this approach doesn’t work when node to deleted is last node. Since the question says intermediate node, we can use this approach.


Quiz of this Question

sudo-gate-course

My Personal Notes arrow_drop_up
Recommended Articles
Page :