題目
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}.
解析
解決這個問題首先使用快慢指針找到數列中點,然後將後半部分反序,最後將前半部分和後半部分進行連接。
c++實現
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
if (!head || !head->next) return;
ListNode* fast = head, *slow = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
// 將slow指針後的鏈表反序連接
ListNode* pre = slow->next;
if (pre->next) {
ListNode* nex = pre->next;
pre->next = NULL; // 將原鏈表斷開,如不斷開,將會死循環
while (nex) {
pre = nex->next;
nex->next = slow->next;
slow->next = nex;
nex = pre;
}
}
// 將head指針和slow指針連接
ListNode* p = head, *q = slow->next;
while (p && q) {
slow->next = q->next;
q->next = p->next;
p->next = q;
q = slow->next;
p = p->next->next;
}
}
};