Created
November 8, 2014 18:30
-
-
Save eleco/e4fc67abf77d388177b7 to your computer and use it in GitHub Desktop.
reverse singly list recursively and iteratively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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