Public · Protected · Private
Reverse a Singly linkedList
Type: Public  |  Created: 2008-07-22  |  Frozen: Yes
« Previous Public Blog Next Public Blog »
Comments
  • Problem statement: How to reverse a singly linked list.
    2008-07-22 01:52
  • //This is a simple linked list 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; }
    2008-07-22 01:53
  • //This is how we Fill , call , test it. 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; }
    2008-07-22 01:54
  • Interesting. 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);
    2008-07-22 02:00
  • Someone recently asked how to reverse a circular linkedlist. 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.
    2008-08-22 11:56
This blog is frozen. No new comments or edits allowed.