LeetCode(143): Recorder List

Recorder List: Given a singly linked list L: L0L1→…→Ln-1Ln,reorder it to: L0LnL1Ln-1L2Ln-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}.

题意:给定一个链表,把最后一个结点插入到第一个结点后面,倒数第二个结点插入到原链表第二个结点后面,依次类推。

思路:利用快慢指针的方法找到链表的中点,然后逆转中点右边的链表,然后将两个链表合并。

代码:

public void reorderList(ListNode head) {
        if(head == null || head.next == null) return;

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

        ListNode mid = slow.next;
        ListNode cur = mid;
        ListNode pre = null;
        while(cur != null){
            ListNode post = cur.next;
            cur.next = pre;
            pre = last;
            cur = post;
        }
        slow.next = null;

        while(head != null && pre != null){
            ListNode next1 = head.next;
            head.next = pre;
            pre = pre.next;
            head.next.next = next1;
            head = next1;
        }
        
    }

posted @ 2016-01-18 19:16  Lewisr  阅读(200)  评论(0)    收藏  举报