/**
* 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) {
int n = 0,i = 0;
auto p=head;
while(p){
p=p->next;
n++;
}
p=head;
stack<ListNode*> S;
while(p){
auto temp=p->next;
if(i>=(n/2)){
S.push(p);
p->next=NULL;
}
p=temp;
i++;
}
p=head;
if(n%2==1){
for(i=0;(i<n/2)&&!S.empty()&&p;i++){
auto q = S.top();
S.pop();
auto temp=p->next;
q->next=temp;
p->next=q;
p=temp;
}
}
else{
for(i=0;(i<n/2-1)&&!S.empty()&&p;i++){
auto q = S.top();
S.pop();
auto temp=p->next;
q->next=temp;
p->next=q;
p=temp;
}
}
}
};
143. 重排链表
最新推荐文章于 2024-08-15 05:02:54 发布