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}.
重排链表,设链表长为n+1,要求第n-m个结点(n,m = 0,1,2,……n)插入到第m个结点后。
其实就是沿着链表中点对称插入重排,而链表的特殊之处就在于不能走回头路,但我们可以把链表后半部分进行逆序,然后把前后两部分的链表合并就ok了。过程:
1-2-3-4-5-6-7-8
↓
1-2-3-4
5-6-7-8
↓
1-2-3-4
8-7-6-5
↓
1-8-2-7-3-6-4-5
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next) return;
//找中点
ListNode *slow = head, *fast = head;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
//分割链表成两部分
ListNode *midNode = slow->next;
slow->next = NULL;
//翻转链表后半部分
ListNode *pre = midNode, *cur;
while (pre && (cur = pre->next))
{
pre->next = cur->next;
cur->next = midNode;
midNode = cur;
}
//插入
cur = head;
ListNode *subCur;
while ((subCur = midNode))
{
midNode = subCur->next;
subCur->next = cur->next;
cur->next = subCur;
cur = cur->next->next;
}
//return head;
}
};