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) return ;
//分为两部分
ListNode *fast=head;
ListNode *slow=head;
while(1){
fast=fast->next;
if(fast==NULL)
break;
fast=fast->next;
if(fast==NULL)
break;
slow=slow->next;
}
if(slow==NULL) return;
// 后半部分翻转
ListNode *cur=slow;
ListNode *pre=slow->next;
cur->next=NULL;
while(pre!=NULL){
ListNode *temp=pre->next;
pre->next=cur;
cur=pre;
pre=temp;
}
//合并两个链表
ListNode *first=head;
ListNode *second=cur;
while(first!=NULL && second!=NULL && first!=second){
ListNode *temp=second->next;
second->next=first->next;
first->next=second;
first=second->next;
second=temp;
}
return ;
}
};