Wednesday, January 26, 2011

How to reverse a linked list

If you go for an interview and the position which you are interviewing for is r&d focus, then most likely they will ask you some very basic technologies,data structures.  Which you might learned from your uni, but after so many years of working, you almost forget about it.

Recently I came across a question: how to reverse a linked list?

Linked list is quite easy ,  if you don't know about it , you can go to http://en.wikipedia.org/wiki/Linked_list to read more.

From the question you can know , that the linked list which require you to reverse is single linked list.  cause double linked list, there is no point to reverse.

They give me a marker , and ask me to write down the function on a white board. I spend around 10 minutes and didn't get it right, then they lost patience.   the problem for me , is  I am not used to write any code on a board....

So today I create a function to reverse a linked list. Include build the linked list, traverse , and reverse , it totally take me around half an hour in front of my PC.

First of all , we need to define a class which can be used to represent a linked list.

internal class Node
{
public Node(string strName)
{
this._name = strName;
}

private string _name = string.Empty;
public string Name
{
get{return this._name;}
set{this.Name = value;}
}

private Node _next = null;
public Node next
{
get{return this._next;}
set{this._next = value;}
}

public void setNext(Node node)
{

this.next = node;

}
}

internal class LinkedList
{
public string[] arrList = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
private Node _root = null;
public LinkedList ()
{
//build the link list
_root = new Node(arrList[0]);
Node indicator = _root;
for(int i=1;i<arrList.Length;i++)
{
Node tmp = new Node(arrList[i]);
indicator.setNext(tmp);
indicator = tmp;
}
}

public Node Root
{
get
{
return _root;
}
}

public void Traverse(Node root)
{
if(root != null)
{
while(root.next != null)
{
Console.Write("{0},",root.Name);
root = root.next;
}
Console.WriteLine("{0}",root.Name);
}
}
                //This the
public void Reverse()
{
Node indicator = _root;
Node temp = null;
while(indicator.next != null)
{
Node temp1 = indicator.next;
indicator.next = temp;
temp = indicator;
indicator = temp1;
}
indicator.next = temp;
_root = indicator;
}
}

There are also some interesting questions regarding linked list. for example:
1.How you can determinate whether there is a loop in your linked list?
2.How to find out the node which cause loop?

I will post the functions later.

No comments:

Post a Comment