码迷,mamicode.com
首页 > 其他好文 > 详细

143. Reorder List

时间:2015-04-18 08:41:27      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}.

先找到终点,将后半段反转,然后merge前半段和后半段。

public class ReorderList {

    public void reorderList(ListNode head) {

        if (head == null) {

            return;

        }

        ListNode mid = findMid(head);

        ListNode head1 = head;

        ListNode head2 = reverseIterative(mid.next);

        mid.next = null;

        head = merge(head1, head2).next;

    }

    

    private ListNode merge(ListNode head1, ListNode head2) {

        ListNode head = new ListNode(0);

        head.next = head1;

        while(head1 != null && head2 != null) {

            ListNode next1 = head1.next;

            ListNode next2 = head2.next;

            head1.next = head2;

            head2.next = next1;

            head1 = next1;

            head2 = next2;

        }

        return head.next;

    }

    

    private ListNode findMid(ListNode head) {

        ListNode slow = head;

        ListNode fast = head;

        while(fast != null && fast.next != null) {

            slow = slow.next;

            fast = fast.next.next;

        }

        return slow;

    }

    

    private ListNode reverseIterative(ListNode head) {

        ListNode pre = null;

        while (head != null) {

            ListNode tmp = head.next;

            head.next = pre;

            pre = head;

            head = tmp;

        }

        return pre;

    }

}

143. Reorder List

标签:

原文地址:http://www.cnblogs.com/shini/p/4436575.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!