Let be a function that deletes a node in a singly-linked list given a pointer to the node and a pointer to the head of the list. Similarly, let be another function that deletes a node in a doubly-linked list given a pointer to the node and a pointer to the head of the list.
Let denote the number of nodes in each of the linked lists. Which one of the following choices is about the worst-case time complexity of and
View worked solution
Answer: D
To determine the worst-case time complexity of deleting a node from a singly-linked list () and a doubly-linked list (), let us analyze the steps required for each:
1. Singly-Linked List ()
- To delete a given node from a singly-linked list, we must update the
nextpointer of its predecessor node to point to . - Since a singly-linked list only has forward pointers, we cannot directly access the predecessor of .
- We must traverse the list starting from the
headto find the predecessor node such that . - In the worst case (for example, when is the last node in the list), this traversal requires visiting all nodes, which takes time.
- Note: While a trick exists to copy the data of the next node into and delete the next node in time, this trick fails if is the last node of the list. Thus, the worst-case time complexity remains .
2. Doubly-Linked List ()
- In a doubly-linked list, every node contains pointers to both its successor (
next) and its predecessor (prev). - We can directly access the predecessor of using and the successor using .
- The deletion can be performed in constant time by updating the pointers:
if (P->prev != NULL) P->prev->next = P->next; if (P->next != NULL) P->next->prev = P->prev; - Since no traversal is needed, the worst-case time complexity is .
Thus, is and is .
Free practice · Your answers on this page are not saved.
