题目链接:https://leetcode-cn.com/problems/reorder-list/ 题目如下:
class Solution {
public:
void reorderList(ListNode* head) {
if(!head||!head->next) return;
auto fast=head,slow=head;
while(fast->next&&fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
cout<<slow->val<<endl;
auto temp=slow->next;
slow->next=nullptr;
auto p2=reverse(temp);
auto p1=head;
ListNode* temp1,*temp2;
while(p1&&p2){
temp1=p1->next;
temp2=p2->next;
p1->next=p2;
p1=temp1;
p2->next=p1;
p2=temp2;
}
}
ListNode* reverse(ListNode* head){
ListNode* pre=nullptr;
ListNode* cur=head;
while(cur){
auto temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
|