leetcode 之Reorder List(25)
找到中间结点,将后半部分反转接入即可。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
ListNode *reoderList(ListNode* head) { if (head == nullptr || head->next == nullptr)return head; //找到中间结点的方法很巧妙 ListNode *slow = head, *fast = head,*prev=nullptr; while (fast&&fast->next) { prev = slow; slow = slow->next; fast = fast->next->next; } prev->next = nullptr;//从中间断开 //将后半部分翻转 slow = reverse(slow); //再将两段进行合并 ListNode *curr = head; while (curr->next) { ListNode *tmp = curr->next; curr->next = slow; slow = slow->next; curr->next->next = tmp; curr = tmp; } curr->next = slow; return head; }