题解 | #链表的奇偶重排#
链表的奇偶重排
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 || !head->next) return head; ListNode* oddHead = new ListNode(0); ListNode* evenHead = new ListNode(0); ListNode* odd = oddHead, *even = evenHead, *curr = head; # 创建头结点是为了后面的拼接 int count = 1; // 通过计数判断是奇数位还是偶数位 while (curr) { if (count % 2 == 1) { // 奇数位 odd->next = curr; odd = odd->next; } else { // 偶数位 even->next = curr; even = even->next; } curr = curr->next; count++; } even->next = nullptr; // 确保偶数链表尾部为null odd->next = evenHead->next; // 连接奇数链表和偶数链表 ListNode* result = oddHead->next; delete oddHead; // 清理临时节点 delete evenHead; return result; } };
数据结构练习 文章被收录于专栏
数据结构练习