Site Search:

SolutionFour.java


/* reverse head -> 1 -> 2 -> 3 -> 4 to head -> 4 -> 3 -> 2 -> 1
 * 
 * in place reverse 
 * 
 * step 1. change the node 1's next to null
 * step 2. change node 2's next to node 1
 * step 3. change node 3's next to node 2
 * ...
 * finally. change head's next to node 4
 * 
 * The reverse method traversals the linked list once,
 * the time complexity is O(N).
 * 
 * This solution didn't create a new linked list, it changes the node's next value in place,
 * the space complexity is O(1).
 * 
 * */

public class SolutionFour {
    public static MyNode reverse(MyNode head) {
        if(head == null || head.next == null) return head;
        MyNode pre = head.next;
        MyNode current = pre.next;
        MyNode next = null;
        //set the tail node
        pre.next = null;
        
        //have the current node point to previous node
        while(current != null) {
            next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        
        //have the head point to the last node of the original linked list
        head.next = pre;
        return head;
    }
    
    public static void main(String...args) {
        MyNode head = createLinkedList();
        MyNode preHead = new MyNode(0, head.next);
        printResult(head);
        head = reverse(head);
        printResult(head);
        printResult(preHead);
    }
    
    public static void printResult(MyNode head) {
        if(head == null) return;
        MyNode current = head;
        System.out.println();
        while (current.next != null) {
            current = current.next;
            System.out.print(current.value + " ");
        }
    }
    
    public static MyNode createLinkedList() {
        MyNode head = new MyNode(0, null);
        MyNode next = new MyNode(1, null);
        head.next = next;
        
        next.next = new MyNode(2, null);
        next = next.next;
        
        next.next = new MyNode(3, null);
        next = next.next;
        
        next.next = new MyNode(4, null);
        next = next.next;
        
        next.next = new MyNode(5, null);
        next = next.next;
        
        next.next = new MyNode(6, null);
        next = next.next;
        
        return head;
    }

}