题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/** 利用两个栈实现
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <stack>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* oddEvenList(ListNode* head) {
// write code here
if (head==nullptr||head->next==nullptr) {
return head;
}
stack<int> st1,st2;
auto* Odd=new ListNode(-1);
auto* Even=new ListNode(-1);
Odd->next=nullptr;
Even->next=nullptr;
int flag=0;
while (head!=nullptr) {
if (flag==0) {
st1.push(head->val);
flag=1;
}
else {
st2.push(head->val);
flag=0;
}
head=head->next;
}
while (!st1.empty()) {
ListNode* temp=new ListNode(st1.top());
temp->next=Odd->next;
Odd->next=temp;
st1.pop();
}
while (!st2.empty()) {
ListNode* temp=new ListNode(st2.top());
temp->next=Even->next;
Even->next=temp;
st2.pop();
}
ListNode* p=Odd->next;
while (p->next!=nullptr) {
p=p->next;
}
p->next=Even->next;
return Odd->next;
}
};


查看24道真题和解析