Site Search:

ExtendSolutionFive.java


/* reverse linked list 1 -> 2 -> 3 -> 4 to 4 -> 3 -> 2 -> 1
 * notice there is no head node
 * 
 * reverse by inserting node behind head
 * 
 * traversal the linked list, remove the current node, 
 * insert it before the head node.
 * 
 * change 1 -> 2 -> 3 -> 4 
 * to     2 -> 1 -> 3 -> 4
 * then   3 -> 2 -> 1 -> 4
 * then   4 -> 3 -> 2 -> 1
 * 
 * The reverse method traversals the linked list once,
 * the time complexity is O(N).
 * 
 * This solution didn't create a new linked list,
 * the space complexity is O(1).
 * 
 * */
public class ExtendSolutionFive {
    public static MyNode reverse(MyNode head) {
        if(head == null || head.next == null) return head;
        MyNode pre = head;
        MyNode current = head.next;
        while(current != null) {
            //remove the current node
            pre.next = current.next;
            //set the current node as head
            current.next = head;
            head = current;
            //advance one step
            current = pre.next;
        }
        
        return head;
    }
    
    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;
    }
}