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 1234 --> 1423
java:
package leetcode8.reorderList;
public class Solution {
public static void reorderList(ListNode head){
if (head==null || head.next==null)
return;
ListNode fast=head.next;
ListNode slow=head;
while(fast!=null && fast.next!=null){//找到中间节点,利用快慢指针
fast=fast.next.next;
slow=slow.next;
}
ListNode p=slow.next;//断链,翻转后半部分
slow.next=null;
ListNode pre=null;
ListNode pcur=p.next;
while(p!=null){
pcur=p.next;
p.next=pre;
pre=p;
p=pcur;
}
ListNode l1 = head;
ListNode l2 = pre;
while (l1 != null && l2 != null) {
ListNode l1Next = l1.next;
ListNode l2Next = l2.next;
l1.next = l2;
l2.next = l1Next;
l1 = l1Next;
l2 = l2Next;
}
}
}
总结:思路如下:利用快慢指针找到中间节点,对中间节点的下一节点到末尾节点这一段翻转,从中间节点断链,对两段链进行合并即可,本题是对链表操作很综合的一个问题,对寻找链表的中间节点,翻转,合并要多看多写