题解 | #链表的奇偶重排#
链表的奇偶重排
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) { // write code here if (head == NULL) return NULL; if (head->next == NULL)return head; if (head->next->next == NULL)return head; ListNode* odd = head, * even = head->next; ListNode* lefthead = new ListNode(0), * righthead = new ListNode(0); ListNode* l = lefthead, * r = righthead; ListNode* ltail, * rtail; while (odd || even) { ltail = odd; rtail = even; if (odd->next) { //这里不用判断odd是否存在,原因是只要能进循环odd就必然存在,而even不一定 odd = odd->next->next; } else { odd = odd->next; } if (even) { if (even->next) { even = even->next->next; } else { even = even->next; } } if (ltail) { ltail->next = NULL; l->next = ltail; l = l->next; } if (rtail) { rtail->next = NULL; r->next = rtail; r = r->next; } } ltail->next = righthead->next; return lefthead->next; } };
采用奇偶双指针的思路,沿着链表以步长为2前进,每前进一次就使上一步的结点断裂出去,新建两个头指针用于接收断裂下来的结点,最后合并两个链表。空间复杂度为常数,时间复杂度为On。