/** * 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) { // write code here auto temp=head; auto first=new ListNode(0); auto second=new ListNode(0); ListNode* firstHead=first; ListNode* secondHead=second; int count=0; while(temp){ count++; if(count%2){ first->next=new ListNode(temp->val); first=first->next; } else{ second->next=new ListNode(temp->val); second=second->next; } temp=temp->next; } //将第一个链表的头节点删除 if(firstHead){ temp=firstHead->next; firstHead->next=nullptr; delete firstHead; firstHead=temp; } //将第二个链表的头节点删除 if(secondHead){ temp=secondHead->next; secondHead->next=nullptr; delete secondHead; secondHead=temp; } //将两个链表合并 if(firstHead&&secondHead){ first->next=secondHead; } //打印 printList(firstHead); printList(secondHead); return firstHead; } void printList(ListNode* head){ while(head){ std::cout<<head->val<<" "; head=head->next; } std::cout<<endl; } };