Reverse Second Half of LinkList

/**
 * Created by RuiG on 11/19/16.
 */
public class ReverseSecondHalf {
    public static void main(String[] args) {
        Node head = new Node(5);
        Node n1 = new Node(7);
        Node n2 = new Node(8);
        Node n3 = new Node(6);
        Node n4 = new Node(3);
        Node n5 = new Node(4);
        Node n6 = new Node(2);
//        Node n7 = new Node(8);
        head.next = n1;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
//        n6.next = n7;

        Node ans = reverseSecond(head);
        while (ans != null) {
            System.out.print(ans.val + "->");
            ans = ans.next;
        }
    }

    public static Node reverseSecond(Node head) {
        // dummy-1-2-3-4-5-6-7
        // slow: dummy, 1, 2, 3, 4
        // fast: dummy, 2, 4, 6, null
        Node dummy = new Node(-1);
        dummy.next = head;
        Node slow = dummy, fast = slow, prev = null;

        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        slow.next = reverse(slow.next);

        return dummy.next;
    }

    public static Node reverse(Node head) {
        Node prevNode = null, curNode = head, nextNode = null;
        while (curNode != null) {
            // perfect concat four steps
            nextNode = curNode.next;
            curNode.next = prevNode;
            prevNode = curNode;
            curNode = nextNode;
        }
        return prevNode;
    }
}

class Node {
    Node next;
    int val;

    public Node (int val) {
        this.val = val;
        this.next = null;
    }
}

results matching ""

    No results matching ""