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

Reorder List

时间:2015-03-11 16:58:37      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

Reorder List

问题:

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.

思路:

  使用HashMap记录位置,数学简易推导,进行List的变换

我的代码:

技术分享
public class Solution {
    public void reorderList(ListNode head) {
        if(head == null)    return;
        int count = 0;
        HashMap<Integer,ListNode> hm = new HashMap<Integer,ListNode>();
        while(head != null)
        {
            hm.put(count++,head);
            head = head.next;
        }
        int sum = count - 1;
        for(int i = 0; i < count/2; i++)
        {
            ListNode cur = hm.get(i);
            ListNode next = hm.get(i + 1);
            ListNode last = hm.get(sum - i);
            cur.next = last;
            last.next = next;
            next.next = null;
        }
        return;
    }
}
View Code

他人代码:

技术分享
public class Solution {

    private ListNode start;

    public void reorderList(ListNode head) {

        // 1. find the middle point
        if(head == null || head.next == null || head.next.next == null)return;

        ListNode a1 = head, a2 = head;

        while(a2.next!=null){
            // a1 step = 1
            a1 = a1.next;
            // a2 step = 2
            a2 = a2.next;
            if(a2.next==null)break;
            else a2 = a2.next;
        }
        // a1 now points to middle, a2 points to last elem

        // 2. reverse the second half of the list
        this.reverseList(a1);

        // 3. merge two lists
        ListNode p = head, t1 = head, t2 = head;
        while(a2!=a1){ // start from both side of the list. when a1, a2 meet, the merge finishes.
            t1 = p;
            t2 = a2;
            p = p.next;
            a2 = a2.next;

            t2.next = t1.next;
            t1.next = t2;
        }
    }

    // use recursion to reverse the right part of the list
    private ListNode reverseList(ListNode n){

        if(n.next == null){
            // mark the last node
            // this.start = n;
            return n;
        }

        reverseList(n.next).next = n;
        n.next = null;
        return n;
    }
}
View Code

学习之处:

  • 他人的代码的思路更好,因为节省了空间,最后还是转换成了追击问题,通过追击问题,确定中间点进行分割,前面List和反转后的后面List进行Merge

Reorder List

标签:

原文地址:http://www.cnblogs.com/sunshisonghit/p/4330191.html

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