Skip to content

Instantly share code, notes, and snippets.

@nashid
Created November 3, 2016 22:29
Show Gist options
  • Save nashid/b49647b76a388995d29422e93931f238 to your computer and use it in GitHub Desktop.
Save nashid/b49647b76a388995d29422e93931f238 to your computer and use it in GitHub Desktop.
ReverseLinkedList.java
package kata.list.reverse;
class Node {
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
public class LinkedListReverse {
/*
* @params : node - a linked list
* @output : return the reversed linked list
*/
public static Node reverse(Node node) {
if (node == null || node.next == null ) {
return node;
}
Node prev = null;
Node current = node;
Node next;
while (current.next != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
current.next = prev;
return current;
}
public static void main(String args[]) {
Node three = new Node(3, null);
Node two = new Node(2, three);
Node one = new Node(1, two);
Node reversed = reverse(one);
print(reversed);
System.out.println();
three = new Node(3, null);
reversed = reverse(three);
print(reversed);
System.out.println();
three = new Node(3, null);
two = new Node(2, three);
reversed = reverse(two);
print(reversed);
}
private static void print(Node reversed) {
Node node = reversed;
while (node !=null) {
System.out.print( node.value + " ");
node = node.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment