Here is code that should reverse Linked list:
Linked list class:
class Node
{
int ID;
string name;
Node next;
}
First option (recursive function):
Node Reverse(Node root)
{
PutOnTop(root, root.Next)
}
Node PutOnTop(Node newRoot, Node current)
{
Node next = current.Next;
current.Next = newRoot;
if(next.Next!=null)
PutOnTop(current,next);
}
Second option (without using recursive function):
Node Reverse(Node root)
{
Node current = root.next;
Node prev = root;
while(current!=null)
{
Node next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
}
Linked list class:
class Node
{
int ID;
string name;
Node next;
}
First option (recursive function):
Node Reverse(Node root)
{
PutOnTop(root, root.Next)
}
Node PutOnTop(Node newRoot, Node current)
{
Node next = current.Next;
current.Next = newRoot;
if(next.Next!=null)
PutOnTop(current,next);
}
Second option (without using recursive function):
Node Reverse(Node root)
{
Node current = root.next;
Node prev = root;
while(current!=null)
{
Node next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
}
Comments