/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */class Solution { ListNode* reverseList(ListNode* head) { if (head == nullptr) return head; ListNode* cur = head; ListNode* pre = nullptr; while (cur) { ListNode* tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; }public: // 思路,将后面的一半进行翻转,然后进行z型连接 // 题解见此:https://leetcode-cn.com/problems/LGjMqU/solution/jian-zhi-offer-2-mian-shi-ti-26-shu-zhon-py79/ void reorderList(ListNode* head) { // 这里加个虚拟头节点是为了使后半段比前半段少1或相等 ListNode* dummy = new ListNode(0, head); ListNode* slow = dummy; ListNode* fast = dummy; while (fast != nullptr && fast->next != nullptr) { fast = fast->next->next; slow = slow->next; } delete dummy; dummy = nullptr; ListNode* headB = slow->next; // slow的下一个就是后半段 slow->next = nullptr; // 安放指针,没有这一步会报错... ListNode* p2 = reverseList(headB); // 翻转后半段 ListNode* p1 = head; // p1就是左半段的头 ListNode* p3 = nullptr; // p3辅助---代表下一个要串的节点 // p2就是要当前轮次要串的节点,串完结束 while (p2) { p3 = p1->next; // p3记录下一个要串节点 p1->next = p2; // 串 p1 = p1->next; // p1往前走一步 p2 = p3; // p2走到p3上,继续搞 } }};