问题描述
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}.
问题分析
此题是要将链表后半段逆转,之后再插入前半段。
此题拥有一个额外条件,不能使用别的空间,否则将后半段直接进栈即可,会容易很多。主要分为三步:
使用快慢指针找到链表中点
逆转后半段链表
将后半段链表插入到前半段中
代码实现
public void reorderList(ListNode head) {
if (head == null||head.next==null) return;
ListNode fast, slow, mid;//快慢指针,找中点mid
fast = slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}//fast到尾部,slow到中点
mid = slow;
ListNode preCur=slow.next;
while (preCur.next!=null){
ListNode cur=preCur.next;
preCur.next=cur.next;
cur.next=mid.next;
mid.next=cur;
}//逆转后半段链表
ListNode a=head;
ListNode b=mid.next;
while (a!=mid){
mid.next=b.next;
b.next=a.next;
a.next=b;
a=b.next;
b=mid.next;
}//后半段插入前半段
}