描述
给定一个单链表L: L0→L1→…→Ln-1→Ln,
重新排列后为:L0→Ln→L1→Ln-1→L2→Ln-2→…
必须在不改变节点值的情况下进行原地操作。
样例
给出链表 1->2->3->4->null,重新排列后为1->4->2->3->null。
挑战
Can you do this in-place without altering the nodes’ values?
代码
1.将链表拆成两半。
2.将后一半链表逆序。
3.再把逆序后的链表一个一个地每隔一个插入前一半链表中。
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: nothing
*/
public void reorderList(ListNode head) {
// write your code here
if(head==null||head.next==null){
return;
}
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
ListNode q=slow.next;
slow.next=null;
slow=q;
//逆序
ListNode pre=null;
while(slow!=null){
ListNode next=slow.next;
slow.next=pre;
pre=slow;
slow=next;
}
//一个个插入左链表
ListNode cur=head,reserve=pre;
while(reserve!=null){
ListNode p=reserve;
reserve=reserve.next;
p.next=cur.next;
cur.next=p;
cur=p.next;
}
}
}