My Java Solution


  • 0
    C

    3 Steps:

    1 calculate the length of the list lenght

    2 reverse the last k ( length / 2) nodes

    3 merge the first length - k nodes and the reversed last k nodes

    public void reorderList(ListNode head) {
        int len = 0;
        ListNode p = head;
        while(p != null) {
            p = p.next;
            len++;
        }
        if(len < 3) return;
        int k = len / 2;
        p = head;
        for(int i = 0; i < len - k - 1; i++) {
            p = p.next;
        }
        ListNode pre = p.next;
        ListNode node = pre.next;
        pre.next = null;
        p.next = null;
        while(node != null) {
            ListNode tmp = node.next;
            node.next = pre;
            pre = node;
            node = tmp;
        }
        p = head;
        for(int i = 0; i < k; i++) {
            ListNode t1 = p.next;
            ListNode t2 = pre.next;
            p.next = pre;
            pre.next = t1;
            p = t1;
            pre = t2;
        }
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.