题目描述
思路分析
链表反转+类双指针
先把后半段反转,然后前半段依次间隔插入后半段。注意奇偶和边界问题。
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
if(!head||!head->next||!head->next->next) return;
int cnt=0;
for(auto p=head;p;p=p->next) cnt++;
auto mid=head;
for(int i=0;i<(cnt+1)/2-1;i++) mid=mid->next;
auto a=mid,b=mid->next;
for(int i=0;i<cnt/2;i++){ //反转后半段链表
auto c=b->next;
b->next=a,a=b,b=c;
}
auto p=head,q=a;
for(int i=0;i<cnt/2;i++){
auto ne=q->next;
q->next=p->next;
p->next=q;
p=q->next;
q=ne;
}
if(cnt%2) mid->next=NULL;
else mid->next->next=NULL;
}
};