Last active
August 29, 2015 14:15
-
-
Save fatihsokmen/95d120cad7371ddb6b37 to your computer and use it in GitHub Desktop.
Reversing singly-linked list
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 LinkedList { | |
private Node head = null; | |
public LinkedList() { | |
head = null; | |
} | |
public void reverse() { | |
if (head == null) { | |
return; | |
} | |
Node oldHead = head; | |
reverseInternal(head.next).next = oldHead; | |
oldHead.next = null; | |
} | |
private Node reverseInternal(Node node) { | |
if (node.next == null) { | |
head = node; | |
return node; | |
} | |
reverseInternal(node.next).next = node; | |
return node; | |
} | |
public Node add(int x) { | |
return add(x, null); | |
} | |
public Node add(int x , Node next) { | |
if (head == null) { | |
head = new Node(x, next); | |
return head; | |
} else { | |
Node c = head; | |
while (c.next != null) { | |
c = c.next; | |
} | |
c.next = new Node(x, next); | |
return c.next; | |
} | |
} | |
public static class Node { | |
Node next; | |
int value; | |
public Node(int value) { | |
this.value = value; | |
} | |
public Node(int value, Node next) { | |
this.value = value; | |
this.next = next; | |
} | |
public String toString() { | |
return String.valueOf(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment