Site Search:

ExtendSolutionTwo.java


/* reverse 1 -> 2 -> 3 -> 4 to 4 -> 3 -> 2 -> 1
 * notice there is no head node
 * 
 * reverse while traversal
 * 
 * The reverse method traversals the linked list once, 
 * the time complexity is O(N).
 * 
 * This solution preserves original linked list
 * the space complexity is O(N).
 * 
 * 
 * */
public class ExtendSolutionTwo {
    public static MyNode reverse(MyNode head) {
        if(head == null || head.next == null) return head;
        //special treatment for tail
        MyNode pre = new MyNode(head.value, null);
        MyNode current = pre;
        while(head.next != null) {
            //create a new node, pointing to previous node
            current = new MyNode(head.next.value, current);
            head = head.next;
        }
        return current;
    }
    
    public static void main(String...args) {
        MyNode head = createLinkedList();
        MyNode preHead = new MyNode(head.value, head.next);
        printResult(head);
        head = reverse(head);
        printResult(head);
        printResult(preHead);
    }
    
    public static void printResult(MyNode head) {
        System.out.println();
        if(head == null) return;
        while(head != null) {
            System.out.print(head.value + " ");
            head = head.next;
        }
    }
    
    public static MyNode createLinkedList() {
        MyNode head = new MyNode(1, null);
        MyNode current = head;
        for(int i = 2; i <= 4; i++) {
            current.next = new MyNode(i, null);
            current = current.next;
        }
        return head;
    }

}