您的位置:首页 > 其它

[LeetCode] - Reorder List

2014-08-11 10:51 344 查看
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. 拆分。用快慢指针找到链表的中点,然后将链表一分为二。初始条件应该设置为,slow=head, fast=head.next,然后进入while循环。这样出来的结果可以保证:(1)如果链表长度为偶数,则前半部分的长度和后半部分相等;(2)如果链表长度为奇数,则前半部分的长度比后半部分大1。这样的结果方便后面的insert。

2. 反转。对拆分之后的后半部分进行反转。链表反转的算法很常用了,就是加入一个fake,然后把head后面的每个node一个个的插入到fake和fake.next之间就可以了。

3. 插入。将反转之后的后半部分链表插入到前半部分之中。

代码如下:

/**
* Definition for singly-linked list.
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head==null || head.next==null) return;
ListNode second = cut(head);
second = reverse(second);
insert(head, second);
return;
}

public ListNode cut(ListNode head) {
ListNode slow=head, fast=head.next;

// odd->fast==null; even->fast.next==null
// guarantee that the length of 1st half is equal or longer than the 2nd half
while(fast!=null && fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode secHead = slow.next;
slow.next = null;
return secHead;
}

public ListNode reverse(ListNode head) {
ListNode fake = new ListNode(-1);
fake.next = head;
ListNode cur = head.next;
while(cur != null) {
head.next = cur.next;
cur.next = fake.next;
fake.next = cur;
cur = head.next;
}
return fake.next;
}

public void insert(ListNode first, ListNode second) {
while(second != null) {
ListNode temp = second.next;
second.next = first.next;
first.next = second;
first = first.next.next;
second = temp;
}
return;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: