题解 | #链表的奇偶重排#
链表的奇偶重排
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) { ListNode *p = head; ListNode *slow, *fast = nullptr; int count = 1; if (head != nullptr) { if (head->next != nullptr && head->next->next != nullptr) { fast = head->next->next; slow = head->next; while (fast != nullptr) { if (count % 2 != 0) { slow->next = fast->next; fast->next=p->next; p->next = fast; p=fast; fast = slow->next; } else { slow = slow->next; fast = fast->next; } count++; } } // write code here } return head; } };
c++快慢指针,p来存储偶数下标的前一个结点,每当count为奇数次时把快指针指的值插入到p结点后面;count为偶数此时,快慢指针往后移动,直到快指针为空时停止。
#新手小白刷题#