题解 | 链表的奇偶重排
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
#include<vector>
using namespace std;
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* oddEvenList(ListNode* head) {
if(head==nullptr)
return nullptr;
if(head->next==nullptr){
return head;
}
vector<int>data;
ListNode* J=head;
data.push_back(J->val);
while (J->next!=nullptr) {
J=J->next->next;
if(J!=nullptr)
data.push_back(J->val);
else
break;;
}
ListNode* O=head->next;
data.push_back(O->val);
while(O->next!=nullptr){
O=O->next->next;
if(O!=nullptr)
data.push_back(O->val);
else
break;;
}
ListNode* Head=new ListNode(data[0]);
ListNode* curr=Head;
for(int i=1;i<data.size();i++){
curr->next=new ListNode(data[i]);
curr=curr->next;
}
return Head;
}
};