Given a singly linked list L: L 0→L 1→…→L n-1→L n,
reorder it to: L 0→L n →L 1→L n-1→L 2→L n-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}.
题目比较简单,但是要求时间在1s内,空间在32768k内,完全不达标。。。
step1:快慢指针找中点;
step2:链表翻转;
step3:链表合并;
public class Solution {
public void reorderList(ListNode head) {
ListNode slow, quik, cur, pre;
ListNode curHead;
slow = head;
quik = head;
if(head ==null || head.next == null){
return;
}
while(quik.next != null && quik.next.next != null){
quik = quik.next.next;
slow = slow.next;
}
cur = slow.next;
slow.next = null;
pre = null;
while(cur != null){
ListNode curPost = cur.next;
cur.next = pre;
pre = cur;
cur = curPost;
}
curHead = head;
while(curHead != null && pre != null){
ListNode preNext = pre.next;
pre.next = curHead.next;
curHead.next = pre;
curHead = pre.next;
pre = preNext;
}
}
}