Created
September 4, 2019 06:52
-
-
Save sinanduman/bef4a8d6b8e69d78d2e6febdcb43f0a9 to your computer and use it in GitHub Desktop.
Singly LinkedList reverse algorithm using iterative and recursive methods.
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
package algo; | |
public class LinkedListReverse { | |
public static void main(String[] args) throws Exception { | |
Node<Integer> node = new Node(1); | |
node.next = new Node(2); | |
node.next.next = new Node(3); | |
node.next.next.next = new Node(4); | |
node.next.next.next.next = new Node(5); | |
System.out.println(node); | |
//Node(value=1, next=Node(value=2, next=Node(value=3, next=Node(value=4, next=Node(value=5, next=null))))) | |
System.out.println(reverse(node)); | |
//Node(value=5, next=Node(value=4, next=Node(value=3, next=Node(value=2, next=Node(value=1, next=null))))) | |
System.out.println(node); | |
//Node(value=1, next=Node(value=2, next=Node(value=3, next=Node(value=4, next=Node(value=5, next=null))))) | |
System.out.println(reverseRecursion(node, null)); | |
//Node(value=5, next=Node(value=4, next=Node(value=3, next=Node(value=2, next=Node(value=1, next=null))))) | |
} | |
public static Node reverse(Node n) throws Exception { | |
if (n == null) | |
throw new Exception("Node is null"); | |
Node ret = null; | |
while(n != null){ | |
Node tmp = new Node(n.value); | |
ret = new Node(tmp.value, ret); | |
n = n.next; | |
} | |
return ret; | |
} | |
public static Node reverseRecursion(Node n, Node tail) throws Exception { | |
if(n != null){ | |
tail = new Node(n.value, tail); | |
return reverseRecursion(n.next, new Node(tail.value, tail.next)); | |
} | |
return tail; | |
} | |
private static class Node<T> { | |
T value; | |
Node next; | |
public Node() { | |
} | |
public Node(T value) { | |
this.value = value; | |
} | |
public Node(T value, Node next) { | |
this.value = value; | |
this.next = next; | |
} | |
@Override | |
public String toString() { | |
return "Node(value=" + this.value + ", next=" + this.next + ")"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment