Skip to content

Instantly share code, notes, and snippets.

@eleco
Created November 8, 2014 18:30
Show Gist options
  • Save eleco/e4fc67abf77d388177b7 to your computer and use it in GitHub Desktop.
Save eleco/e4fc67abf77d388177b7 to your computer and use it in GitHub Desktop.
reverse singly list recursively and iteratively
public class SinglyListNode {
SinglyListNode next;
String s;
public String toString(){return s;}
public SinglyListNode(String s){this.s=s;}
public static void main(String argsp[]){
SinglyListNode a = new SinglyListNode("a");
SinglyListNode b = new SinglyListNode("b");
SinglyListNode c = new SinglyListNode("c");
a.next = b;
b.next = c;
p(a);
SinglyListNode e =recursiveReverse(a, null);
p(e);
SinglyListNode f = iterativeReverse(e);
p(f);
}
public static void p(SinglyListNode n){
if (n==null) return;
System.out.print(n);
p(n.next);
}
public static SinglyListNode iterativeReverse(SinglyListNode n){
SinglyListNode previous = null;
SinglyListNode current = n;
while (current!=null){
SinglyListNode tmp = current.next;
current.next = previous;
previous = current;
current = tmp;
}
return previous;
}
public static SinglyListNode recursiveReverse(SinglyListNode a, SinglyListNode previous){
if (a.next==null){
a.next = previous;
return a;
}else {
SinglyListNode b = a.next;
a.next = previous;
return recursiveReverse(b, a);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment