/* Recursive Method: 1) Divide the list in two parts - first node and rest of the linked list. 2) Call reverse for the rest of the linked list. 3) Link rest to first. 4) Fix head pointer. */ public class SinglyLinkedListImpl { private Node head; public void add(T element) { Node nd = new Node(); nd.setValue(element); System.out.println("Adding: "+element); Node tmp = head; while(true) { if(tmp == null) { //since there is only one element, both head and //tail points to the same object. head = nd; break; } else if(tmp.getNextRef() == null) { tmp.setNextRef(nd); break; } else { tmp = tmp.getNextRef(); } } } public void traverse() { Node tmp = head; while(true) { if(tmp == null) { break; } System.out.print(tmp.getValue()+"\t"); tmp = tmp.getNextRef(); } } public void reverse() { System.out.println("\nreversing the linked list\n"); Node prev = null; Node current = head; Node next = null; while(current != null) { next = current.getNextRef(); current.setNextRef(prev); prev = current; current = next; } head = prev; } public static void main(String a[]) { SinglyLinkedListImpl sl = new SinglyLinkedListImpl(); sl.add(3); sl.add(32); sl.add(54); sl.add(89); System.out.println(); sl.traverse(); System.out.println(); sl.reverse(); sl.traverse(); } } class Node implements Comparable { private T value; private Node nextRef; public T getValue() { return value; } public void setValue(T value) { this.value = value; } public Node getNextRef() { return nextRef; } public void setNextRef(Node ref) { this.nextRef = ref; } @Override public int compareTo(T arg) { if(arg == this.value) { return 0; } else { return 1; } } }