您的位置:首页 > 其它

leetCode No.143 Reorder List

2016-11-16 12:42 483 查看

题目

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

解题思路

一上手的思路是最简单的想法,定义一个头指针,每次头指针向后跳两个节点,每次在跳之前将链表当前的最后一个节点放在头指针的后面。但是由于是单向链表,每次寻找尾结点都要从头遍历到尾。进一步优化就是在寻找尾节点的时候从当前点向后寻找,这样就不必每次都遍历一次链表了,但是很明显这样的方法仍然较慢,最终依然TLE。

正确的做法是首先用快慢指针法找到链表的中点,然后将中点之后的节点一边遍历,一边就地倒序。最后将后一半的节点插到前面的节点中。时间复杂度是O(n)

代码

public class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null ) {
return;
}
ListNode fast = head;
ListNode slow = head;
ListNode p = head;
ListNode q = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
fast = slow.next;
slow.next = null;
p = fast;
q = fast.next;
fast.next = null;
while (q != null) {
ListNode temp = q.next;
q.next = p;
p = q;
q = temp;
}
q = head;
while (q != null && p != null) {
ListNode temp1 = q.next;
ListNode temp2 = p.next;
p.next = q.next;
q.next = p;
q = temp1;
p = temp2;
}
}
}


相关链接

原题

https://github.com/AndyShan/leetCode" target=_blank>所有题解代码(github)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: