题解 | #链表的奇偶重排#
链表的奇偶重排
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) { if (head == nullptr || head->next == nullptr) return head; auto p = head; auto head1 = head; auto q = head->next; auto head2 = q; while (q->next != nullptr && q->next->next != nullptr) { p->next = q->next; p = q->next; q->next = p->next; q = q->next; } if (q->next == nullptr) { p->next = nullptr; q->next = nullptr; } else { p->next = q->next; p = p->next; q->next = nullptr; } p->next = head2; return head1; } };