It’s 2AM and my insomnia is in full-motion as usual. My random browsing stumbled me upon this site that has a list of good technical/programming questions, and one of which, rehashes some of the memories from my college days. The task is to reverse a linked list, and while the question is asked to be implemented in C, I figured I’d take a stab at it in JAVA (just coz). It’s pretty straight forward, but if anyone has anything to add/comment, I’d like to hear:
package com.ashah.test; public class ReverseLL { static class Node { public int nValue = 0 ; public Node next = null ; public Node(int n) { nValue = n ; } public String toString() { return "[" + nValue + "]" ; } } private static void printLL(Node head) { if (null != head) { System.out.print("{") ; while (null != head) { System.out.print(head) ; head = head.next ; if (null != head) { System.out.print("->") ; } } System.out.println("}") ; } } private static Node reverseLL(Node head) { Node next = null ; Node previous = null ; while (null != head) { // ...keep next since we trash the next pointer next = head.next ; // ...switch the next pointer to point backwards head.next = previous ; // ...move both pointers forward previous = head ; head = next ; } return previous ; } public static void main(String[] args) { java.util.LinkedList ll = new java.util.LinkedList() ; Node n = null ; for (int i=1; i<=10; ++i) { n = new Node(i) ; if (i != 1) { ((Node)ll.get(i-2)).next = n ; } ll.add(n) ; } printLL((Node)ll.getFirst()) ; printLL(reverseLL((Node)ll.getFirst())) ; } }

