Site Search:

SolutionTwo.java


/* reverse head -> 1 -> 2 -> 3 -> 4 to head -> 4 -> 3 -> 2 -> 1
 * 
 * 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 SolutionTwo {
    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);
    }
    
    /*
     * copy current node's next node value to a new node, have it point backwards
     * */
    public static MyNode reverse(MyNode head) {
        if(head == null || head.next == null) return head;
        //first node will become the last node
        MyNode current = head.next;
        //special treatment of the last node
        MyNode newLink = new MyNode(current.value, null);
        
        while(current.next != null) {
            //create a new node with the current node's next node value, the new node should point backwards
            newLink = new MyNode(current.next.value, newLink);
            //move one step further
            current = current.next;
        }
        //update head
        MyNode newHead = new MyNode(0, newLink);
        return newHead;
    }
    
    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;
    }

}