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 断开前半段和翻转后的后半段元素
4 把前半段和翻转后的后半段元素以交叉的方式合并起来
class Solution {
public:
void reorderList(ListNode *head) {
if(head == NULL){
return ;
}
ListNode* p1 = head;
ListNode* p2 = splitList(head);
p2 = revertList(p2);
mergeList(p1,p2);
}
void mergeList(ListNode* p1,ListNode* p2){
while(p2 != NULL){
ListNode* temp = p2;
p2 = p2->next;
temp->next = p1->next;
p1->next = temp;
p1 = p1->next->next;
}
}
ListNode* splitList(ListNode* head){
ListNode* slow = new ListNode(0);
slow->next = head;
ListNode* fast = slow;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
}
if(fast->next != NULL){
slow = slow->next;
fast = fast->next;
}
ListNode* tmp = slow->next;
slow->next = NULL;
return tmp;
}
ListNode* revertList(ListNode* head){
if(head == NULL){
return NULL;
}
ListNode* p = head->next;
head->next = NULL;
ListNode* temp;
while(p != NULL){
temp = p;
p = p->next;
temp->next = head;
head = temp;
}
return head;
}
};