143. 重排链表
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
思路
方法一:
将链表中的各个节点,顺序存储到数组里,空间复杂度高
方法二:
1 快慢指针法找到链表的中间节点p1,断开,即p1.next = null
2 将p1后面的链表反转,可参考206题
3 再将两个链表一一连接
以下代码为方法二的实现
代码
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null){
return;
}
ListNode p1 = head;
ListNode p2 = head;
while (p2 != null && p2.next != null){
p1 = p1.next;
p2 = p2.next.next;
}
//p1是中间节点,反转p1后的
ListNode head2 = p1.next;
p1.next = null;
if (head2.next != null) {
p1 = head2;
p2 = p1.next;
while (p2 != null) {
head2.next = p2.next;
p2.next = p1;
p1 = p2;
p2 = head2.next;
}
head2 = p1;
}
//反转后链表2的头结点是pre
//将1和2两个链表11相连
p1 = head;
p2 = head2;
ListNode p1Cur = head.next;
ListNode p2Cur = head2.next;
while (p2 != null){
p1.next = p2;
p2.next = p1Cur;
p1 = p1Cur;
p2 = p2Cur;
p1Cur = p1Cur.next;
if(p2Cur != null){
p2Cur = p2Cur.next;
}
}
}
}