Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing single linked list in C#

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.

like image 363
Nemo Avatar asked Dec 31 '11 03:12

Nemo


People also ask

Can we reverse a singly linked list?

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.

What is reversing a linked list?

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.

How do you reverse a singly linked list pseudocode?

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.


2 Answers

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.

like image 106
Eric Lippert Avatar answered Sep 23 '22 12:09

Eric Lippert


Node p = root, n = null; while (p != null) {     Node tmp = p.next;     p.next = n;     n = p;     p = tmp; } root = n; 
like image 38
Sergey Kalinichenko Avatar answered Sep 22 '22 12:09

Sergey Kalinichenko