edited by
24,854 views
65 votes
65 votes

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 ?

  1. $O(n)$
  2. $O(\log^2 n)$
  3. $O(\log n)$
  4. $O(1)$
edited by

9 Answers

Best answer
54 votes
54 votes
In the worst case $x$ could be last or second last node, In that case full traversal of the list is required. Therefore answer is (A).

PS: We can simulate the deletion by moving the $x's$ next node data to $x$ and then delete $x's$ next node. But this is technically not the same as DELETING NODE $x$ as mentioned in the question though effect is the same as long as there are a constant number of elements to be moved from $x's$ next node.
selected by
84 votes
84 votes
Since $Q$ is pointing to node $X$, it can de done in $O(1)$ time..

Algo:

$Q \rightarrow data = Q \rightarrow next \rightarrow data$; // Copy the value of next node into $Q$.

$del = Q \rightarrow  next$; // take another pointer variable pointing to next node of $Q$.

$Q \rightarrow next = Q \rightarrow next \rightarrow next$;

$free (del)$;

Correct Answer: $D$
edited by
11 votes
11 votes
Its O(1) only. Just copy next element's data to x ,and delete next.
9 votes
9 votes
Let us say assume ,question it means node with data X: Now we first need to search node with data X in O(n) and then delete.

Let us assume that by X ,it means Node with address X,but the 0(1) method does not delete node with address X.It just modifies node with address X and delete some of its neighbor.

I will go with $ O(n) $ with the above reasoning.
Answer:

Related questions

51 votes
51 votes
4 answers
1
24 votes
24 votes
1 answer
2
23 votes
23 votes
4 answers
3
Ishrat Jahan asked Nov 2, 2014
4,933 views
Which one of the following binary trees has its inorder and preorder traversals as $BCAD$ and $ABCD$, respectively?
62 votes
62 votes
4 answers
4