143Reorder List

来源:互联网 发布:淘宝产品推广公司 编辑:程序博客网 时间:2024/05/19 08:25

题目链接:https://leetcode.com/problems/reorder-list/

题目:

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}.

解题思路:
第一种思路:
1. 第一次遍历链表,将链表结点入栈
2. 第二次遍历链表,同时将栈中结点弹出,插入到当前遍历到的结点后面。例如,遍历第一个结点,弹出最后一个结点,将弹出的结点链接到第一个结点之后。
3. 终止条件为,当前遍历的结点的后继是弹出的结点(偶数个结点的情况),或者当前遍历的结点就是弹出的结点(奇数个结点的情况)
4. 这种方式需要O(n)的空间,运行也比较慢

第二种思路:
将该题拆分为三个基本操作:
1. 将链表从中间断成两半,方法是 walker 和 runner,当 runner 到达链表终点时,walker 到达链表中间。
2. 将后半段链表进行就地转置操作
3. 将前后两段链表归并成一个完整链表
第二种思路更加简洁,可以参考大神的做法:http://blog.csdn.net/linhuanmars/article/details/21503215

代码实现:
第一种:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public void reorderList(ListNode head) {        if(head == null)            return;        LinkedList<ListNode> stack = new LinkedList();        ListNode p = head;        int len = 0;        while(p != null) {            len ++;            stack.push(p);            p = p.next;        }        ListNode q = head;        p = stack.pop();        while(q.next != p && q != p) {            ListNode tmp = q.next;            q.next = p;            p.next = tmp;            q = q.next.next;            p = stack.pop();        }        p.next = null;    }}
13 / 13 test cases passed.Status: AcceptedRuntime: 9 ms

第二种:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public void reorderList(ListNode head) {        if(head == null || head.next == null || head.next.next == null)            return;        ListNode p = head.next;        ListNode q = head.next.next;        while(q != null && q.next != null && q.next.next != null) {            p = p.next;            q = q.next.next;        }        ListNode head2 = p.next;        q = head2;        while(q.next != null) {            ListNode tmp = q.next;            q.next = tmp.next;            tmp.next = head2;            head2 = tmp;        }        p = head;        q = head2;        ListNode h = new ListNode(0);        while(p != null && q != null) {            ListNode tmp1 = p.next;            ListNode tmp2 = q.next;            h.next = p;            p.next = q;            p = tmp1;            q = tmp2;            h = h.next.next;        }        if(p != null) {            h.next = p;            p.next = null;        }    }}
13 / 13 test cases passed.Status: AcceptedRuntime: 3 ms
0 0