1

I was reversing a singly linked list using the following code:

Node prevNode = null;
Node currNode = head;
while (currNode != null) {
    Node next = currNode.next;
    currNode.next = prevNode;
    prevNode = currNode;
    currNode = next;
}
head = prevNode;

Then when I was going through some material about stacks it suggested that reversing any list is best done by using a stack.

It is for sure very easy to visualize that we indeed pop out the elements and push them into a new stack and in the end it is essentially reversed. But which of the two methods is better or would take lesser time?

Riddhesh Sanghvi
  • 1,218
  • 1
  • 12
  • 22
  • One uses O(1) additional space, the other uses O(n) additional space. You decide which is better. – chill Aug 04 '15 at 12:56
  • O(1) would be better for sure. But then is stack recommended for reversing to be better due to easy visualization only? – Riddhesh Sanghvi Aug 04 '15 at 13:01
  • 1
    The industry-standard way is to use `Collections.reverse()`. For practice, everything that teaches you something is recommended. So do both and learn even more :) – Marko Topolnik Aug 04 '15 at 13:05
  • Interesting. Will surely implement stack to reverse linked list :) – Riddhesh Sanghvi Aug 04 '15 at 13:06
  • Be careful not to "overly optimise" when writing code. Machines are performant enough now that we don't need to press every last cycle... The readability of code also has merit - and I wouldn't write a slightly faster routine if the impact of that was to make the routine less obvious to another developer... – Martin Milan Aug 04 '15 at 13:12

2 Answers2

4

By reversing I guess it means making the links between two elements opposite to what it previously was i.e. if it was 1->2->3->4 then it is now 1<-2<-3<-4.

The best way to do it is by breaking this list into two parts namely current and rest, it is a recursive approach.

Time Complexity: O(n), Space Complexity: O(1)

1->2->3->4


1->2->3<-4 (4 being the rest)


1->2<-3<-4


1<-2<-3<-4

You can find the details of this approach here: enter link description here

2

An in-place reversing is always better than using a stack, because we are not using any additional space. However, for an immutable list, the only option to reverse is to use to stack too.

Thomas Mathew
  • 389
  • 2
  • 8