leetcode题解-143. Reorder List

来源:互联网 发布:unity3d数学基础 编辑:程序博客网 时间:2024/05/16 01:48

题目

Given a singly linked list L: 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}.

本题的目的是实现链表的重排,将最后一个元素插在第一个元素后面,倒数第二元素插在第二个后面。。。。一次类推,所以很直观的思路就是把链表分为前后两部分(使用fast和slow两个指针),然后将后面的链表进行翻转,这样就可以按顺序将两个链表合并。链表翻转的题目我们已经做过了,合并的也做过了,拆分成两个链表的也做过了。所以屡清思路之后就是将三个题目结合在一起而已。代码如下所示:

    public void reorderList(ListNode head) {        if(head==null || head.next==null || head.next.next==null)            return;        ListNode fast=head, slow=head, second;        //链表切分成前后两个        while(fast!=null && fast.next!=null){            fast = fast.next.next;            slow = slow.next;        }        second = slow.next;        slow.next = null;        //将后面那个链表进行翻转        ListNode pre=null, next;        while(second != null){            next = second.next;            second.next = pre;            pre = second;            second =  next;        }        //将两个链表合并,把第二个链表的每个元素插在第一个链表的后面即可        fast = head;        while(pre!=null){            next = pre;            pre = pre.next;            next.next = fast.next;            fast.next = next;            fast = fast.next.next;        }    }

此外还看到了一种使用Hash表做的方法,但是效率极低而且完全没有使用到链表里面的特性,这里就放出来参考一下==代码如下所示,不推荐:

   public void reorderList1(ListNode head) {        HashMap<Integer, ListNode> nodeMap = new HashMap<>();        int len = 0;        ListNode p = head;        while (p != null) {            nodeMap.put(len++, p);            p = p.next;        }        int i = 0;        int j = len - 1;        for (; i < j - 1; ++i, --j) {            ListNode tmp = nodeMap.get(i).next;            nodeMap.get(i).next = nodeMap.get(j);            nodeMap.get(j).next = tmp;            nodeMap.get(j - 1).next = null;        }    }
原创粉丝点击