Reorder List (LeetCode)
Question:
https://oj.leetcode.com/problems/reorder-list/
解答:
inplace的解法,想到就是把后半段Linked List反转,然后逐个插入到上半段Linked List中。注意边界条件还有后半段是curr+1. (因为最后剩下不管是两个还是1个,都不需要处理,所以后半段要不比前半段少一个,要不少两个).
找到后半段List的头可以用两个指针,一个一次走一步,一个一次走两步。
class Solution { public: void reorderList(ListNode *head) { if (!head) return; // Find the middle pointer, and reverse the rest list ListNode* curr = head; ListNode* curr2 = head; while (curr2 && curr2->next) { curr = curr->next; curr2 = curr2->next->next; } ListNode* rightHalfHead = curr->next; if (!rightHalfHead) return; curr->next = NULL; // reverse rightHalfHead curr2 = rightHalfHead; while (rightHalfHead->next) { ListNode* next = rightHalfHead->next->next; rightHalfHead->next->next = curr2; curr2 = rightHalfHead->next; rightHalfHead->next = next; } curr = head; while (curr2) { // insert curr2 after curr ListNode* next = curr2->next; curr2->next = curr->next; curr->next = curr2; curr2 = next; curr = curr->next->next; } } };