GATE | GATE-IT-2004 | Question 13
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?
(B) O(log2 n)
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.
Attention reader! Don’t stop learning now. Practice GATE exam well before the actual exam with the subject-wise and overall quizzes available in GATE Test Series Course.
Learn all GATE CS concepts with Free Live Classes on our youtube channel.
// 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