题解 | #链表的奇偶重排#
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/** * 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) { //注意偶链表尾结点的next即可 //保证至少有三个结点 if(head==nullptr || head->next==nullptr || head->next==nullptr){ return head; } ListNode* L1=head; ListNode* L2=head->next; ListNode* p1=L1; ListNode* p2=L2; ListNode* p=L2->next;//用于遍历 int flag=true;//轮回 while(p){ if(flag){ p1->next=p; p1=p; }else{ p2->next=p; p2=p; } flag=!flag; p=p->next; } p2->next=nullptr; p1->next=L2;//连接奇偶链表 return head; } };