I am trying to reverse a linked list. This is the code I have come up with:
public static void Reverse(ref Node root) { Node tmp = root; Node nroot = null; Node prev = null; while (tmp != null) { //Make a new node and copy tmp nroot = new Node(); nroot.data = tmp.data; nroot.next = prev; prev = nroot; tmp = tmp.next; } root = nroot; }
It is working well. Was wondering if it possible to avoid creating new node. Would like to have suggestions on this.
It is not possible to reverse a simple singly linked list in less than O(n). A simple singly linked list can only be reversed in O(n) time using recursive and iterative methods.
In a singly linked list, order is determined by a given node's next property. This property can either reference another node or will point to null if this is the last node in the list. So reversing a linked list, simply means reassigning all the next properties, on every node.
To reverse a linked list all we need to do is change the pointers linking the nodes to point backwards and make the head pointer point to the last node and next pointer of previous head point to null making it the end of the list.
That question gets asked a lot. When I was asked it in my interviews many years ago, I reasoned as follows: a singly-linked list is essentially a stack. Reversing a linked list is therefore a trivial operation on stacks:
newList = emptyList; while(!oldList.IsEmpty()) newList.Push(oldList.Pop());
Now all you have to do is implement IsEmpty and Push and Pop, which are one or two lines tops.
I wrote that out in about twenty seconds and the interviewer seemed somewhat perplexed at that point. I think he was expecting me to take about twenty minutes to do about twenty seconds work, which has always seemed odd to me.
Node p = root, n = null; while (p != null) { Node tmp = p.next; p.next = n; n = p; p = tmp; } root = n;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With