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.merge
中间边界条件调试了许久...
/**
* 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 *slow=head,*fast=head;
while(fast->next&&fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
ListNode *mid=slow->next;
slow->next=NULL;
ListNode *p=NULL;
while(mid){
ListNode *t=mid;
mid=mid->next;
t->next=p;
p=t;
}
mid=p;
p=head;
while(p&&mid){
ListNode *t1=p->next;
ListNode *t2=mid->next;
p->next=mid;
mid->next=t1;
p=t1;
mid=t2;
}
}
};