# 【LeetCode】Reorder List 解题报告

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

/**
* class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/

【题意】

【思路】

【Java代码】

public class Solution {
int cnt = 0;
while (node != null) {
cnt++;
node = node.next;
}

if (cnt < 3) return;//3个以下的结点不需要移动

int k = (cnt - 1) / 2;//需要移动的后k个结点
int i = 1;
while (i++ < cnt - k) {
node = node.next;
}
ListNode begin = node.next;//用begin表示需要移动的后k个结点的开始
node.next = null;//把不需要移动的部分结尾设为null

//把需要移动的k个结点逆序
ListNode pre = begin;
ListNode cur = begin.next;
begin.next = null;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;

begin = cur;
pre = cur;
cur = next;
}

ListNode node2 = begin;
while (node1 != null && node2 != null) {
pre = node1;
cur = node2;

node1 = node1.next;//这两行一定要放在下面两行之前，因为pre和node1指向同一个结点，下面操作会改变node1的next；cur和node2同理
node2 = node2.next;

cur.next = pre.next;//这两行代码是把cur插入到pre后
pre.next = cur;
}
}
}

【感受】

【升级版】

public class Solution {

//把整个链表划分成2个等长的子链表，如果原链表长度为奇数，那么第一个子链表的长度多1
while (fast.next != null) {
fast = fast.next;
if (fast.next != null) fast = fast.next;
else break;
slow = slow.next;
}

slow.next = null;

//翻转第二个子链表
ListNode cur = head2, post = cur.next;
cur.next = null;
while (post != null) {
ListNode tmp = post.next;
post.next = cur;
cur = post;
post = tmp;
}

//将两个子链表合并
while (node2 != null) {
ListNode tmp1 = node1.next;
ListNode tmp2 = node2.next;
node1.next = node2;
node2.next = tmp1;
node1 = tmp1;
node2 = tmp2;
}
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120