Skip to content

Instantly share code, notes, and snippets.

@trekawek
Created April 5, 2014 19:14
Show Gist options
  • Save trekawek/9996641 to your computer and use it in GitHub Desktop.
Save trekawek/9996641 to your computer and use it in GitHub Desktop.
Reversing linked list in place
public class LinkedListReverse {
public static void main(String[] args) {
Node head = addElement("Monday", null);
addElement("Tuesday", head);
addElement("Wednesday", head);
printList(head);
head = reverseList(head);
printList(head);
}
private static Node addElement(Object element, Node head) {
Node newElement = new Node(element);
if (head == null) {
return newElement;
}
Node current = head;
while (current.hasNext()) {
current = current.getNext();
}
current.setNext(newElement);
return head;
}
private static void printList(Node head) {
Node current = head;
while (current != null) {
System.out.print(current.getElement());
if (current.hasNext()) {
System.out.print(", ");
}
current = current.getNext();
}
System.out.println();
}
private static Node reverseList(Node head) {
Node current = head;
Node previous = null;
Node next = null;
while (current != null) {
next = current.getNext();
current.setNext(previous);
previous = current;
current = next;
}
return previous;
}
public static class Node {
private final Object element;
private Node next;
public Node(Object element) {
this.element = element;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public boolean hasNext() {
return next != null;
}
public Object getElement() {
return element;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment