143. Reorder List
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}.
// 分三步:
// 1.找到中间结点
// 2.将右半侧反转
// 3.合并两个链表
/**
* 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 == NULL || head->next == NULL)
return;
// 找到中间结点
ListNode* p1 = head;
ListNode* p2 = head->next;
while(p2 && p2->next){
p1 = p1->next;
p2 = p2->next->next;
}
ListNode* middleHead = p1->next;
p1->next = NULL;
// 反转middleHead开始的部分
ListNode* pPre = NULL;
ListNode* pCur = middleHead;
ListNode* pNext = NULL;
while(pCur){
pNext = pCur->next;
pCur->next = pPre;
pPre = pCur;
pCur = pNext;
}
middleHead = pPre;
// 合并
for (p1 = head, p2 = middleHead; p1; ) {
ListNode* temp = p1->next;
p1->next = p2;
p1 = p2;
p2 = temp;
}
}
};