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}
.
Subscribe to see which companies asked this question
使用快慢指针的方法找到中间点 然后把后面的链翻转 再合成一个
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head==null||head.next==null||head.next.next==null)return;
ListNode fast = head;
ListNode slow = head;
while(true){
fast=fast.next;
if(fast.next==null)break;
fast=fast.next;
if(fast.next==null)break;
slow=slow.next;
}
ListNode tem = slow;
slow=slow.next;
tem.next=null;
ListNode med = slow.next;
if(med.next==null){
med.next=slow;
slow.next=null;
slow=med;
}else{
ListNode pre= med.next;
slow.next=null;
while(pre.next!=null){
med.next=slow;
slow=med;
med=pre;
pre=pre.next;
}
med.next=slow;
pre.next=med;
slow=pre;
}
// head.next=slow;
fast=head;
ListNode tem1 = fast.next;
ListNode tem2 = slow.next;
while(tem1!=null){
fast.next=slow;
slow.next=tem1;
fast=tem1;
slow=tem2;
tem1=fast.next;
tem2=slow.next;
}
fast.next=slow;
}
}