278 views
6 6 votes

A singly linked list contains $n$ nodes. We want to reverse the order of the elements in the linked list by changing links, not by copying all elements into an array.

Which of the following statements is correct?

  1. It can be reversed in $O(n)$ time.
     
  2. It can be reversed in $O(\log n)$ time.
     
  3. It must take $O(n^2)$ time.
     
  4. It is impossible to reverse a linked list without using an extra array.

2 Answers

2 2 votes

To reverse a singly linked list, every node must be visited once because each node’s $\texttt{next}$ pointer may need to be changed. 

This gives a lower bound of $\Omega(n)$.

Using three pointers, $\texttt{prev}$, $\texttt{curr}$, and $\texttt{next}$, the list can be reversed in one traversal. 

Therefore, the time complexity is $O(n)$.

Correct answer : A

0 0 votes

A. Correct. There is a $O(n)$ time method to reverse a singly linked list.
B. Incorrect. It cannot be reversed in $O(\log n)$ time because there are $O(n)$ links to be updated.
C. Incorrect. It need not take $O(n^2)$ time since we already know a method to do it $O(n)$ time.
D. Incorrect. It is possible to reverse a singly linked list in-place.

Answer: A

Answer:
Position:
Show:

Related questions

8 8 votes
2 2 answers
247
247 views
GO Classes asked Jul 6
247 views
Consider the following C-style code fragment for reversing a non-empty singly linked list:curr = front; next = curr->next; prev = NULL; while (curr != NULL) { (*) } front...
6 6 votes
2 2 answers
226
226 views
GO Classes asked Jul 6
226 views
The UNIX editor $\texttt{vi}$ allows searching in both directions, and if the search reaches one end, it wraps around and continues from the other end.If the sequence of ...
6 6 votes
3 3 answers
228
228 views
GO Classes asked Jul 6
228 views
A circular linked list has $n$ nodes. A function prints every node exactly once and stops when it reaches the starting node again.What is the running time of printing the...
7 7 votes
2 2 answers
254
254 views
GO Classes asked Jul 6
254 views
The following function is supposed to reverse a singly linked list:struct node { int data; struct node *next; }; static void reverse(struct node head_ref) { struct node ...