• Reorder List


    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
  • 相关阅读:
    Git_创建版本库
    Git_安装Git
    Git_集中式vs分布式
    Git_git的诞生
    echartShow
    微信小程序红包开发 小程序发红包 开发过程中遇到的坑 微信小程序红包接口的
    vue2.0 $router和$route的区别
    vue移动端开发全家桶
    干货分享:vue2.0做移动端开发用到的相关插件和经验总结
    优秀的基于VUE移动端UI框架合集
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4330191.html
Copyright © 2020-2023  润新知