143. Reorder List

Given a singly linked listL:L0→L1→…→Ln-1→Ln,
reorder it to:L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.

思路:超找中间节点和原地反转list都用上了

找找中间节点的代码:

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

原地反转的代码

        ListNode curr = slow.next;
        slow.next = null;
        ListNode prev = null;
        ListNode next = null;
        while (curr.next!=null){
            //System.out.println(curr.val);
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        curr.next = prev;

整体代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void reorderList(ListNode head) {
        if (head==null||head.next==null){
            return;
        }

        //find the middle
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next!=null&&fast.next.next!=null){
            slow = slow.next;
            fast = fast.next.next;
        }

        //reverse the second
        ListNode curr = slow.next;
        slow.next = null;
        ListNode prev = null;
        ListNode next = null;
        while (curr.next!=null){
            //System.out.println(curr.val);
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        curr.next = prev;

        //merge two list
        ListNode head1 = head;
        ListNode head2 = curr;
        while(head2!=null){
            ListNode head1Next = head1.next;
            ListNode head2Next = head2.next;
            head2.next = head1Next;
            head1.next = head2;
            head1 = head1Next;
            head2 = head2Next;
        }

        return;
    }
}

results matching ""

    No results matching ""