Reverse a Singly linkedList
class SimpleLinkedList
{
public SimpleLinkedList next;
public int value;
public SimpleLinkedList(int v)
{
value = v;
}
}
//This is how we reverse it
SimpleLinkedList reversethis(SimpleLinkedList input)
{
SimpleLinkedList a = null;
SimpleLinkedList b= input;
SimpleLinkedList c= input.next;
while (c != null)
{
b.next = a;
// Here a,b,c will MARCH TO NEXTs
a = b;
b = c;
c = c.next;
}
b.next = a;
return b;
}
SimpleLinkedList root = new SimpleLinkedList(0);
SimpleLinkedList temp = root ;
for (int i = 1; i <= 10; i++)
{
temp.next = new SimpleLinkedList(i);
temp = temp.next;
}
label2.Text = label1.Text = "";
temp = root;
while (temp != null)
{
label1.Text += temp.value.ToString() + "\r\n";
temp = temp.next;
}
root = reversethis(root);
temp = root;
while (temp != null)
{
label2.Text += temp.value.ToString() + "\r\n";
temp = temp.next;
}
Lools like simplest reversal.
One more interesting thing in your function is
This is a way to find if the linked list is having a loop.
Typically
SimpleLinkedList root;
SimpleLinkedList temp = reverseit(root);
if(temp == root) THIS LINKEDLIST HAS A LOOP.
This is a destructive test on loopy linkedlist.
So remedy is calling it again
root = reverseit(root);
Above algorithm can be used--- Except that we will scan until we find the node where we started (Instead of searching for null)
A better solution can be simply put all the nodes into a stack. Then pop them until stack is empty and append it to the first one.