跟上一題一樣,我們可以先找到 list 中點,把後半 list reverse,然後就依序連接前半跟後半的 node。這樣做的好處是效率很高,時間複雜度 O(N),空間複雜度 O(1)。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */classSolution {public:voidreorderList(ListNode* head) {if(!head or!head->next)return; // Find the middle of list ListNode* slow = head; ListNode* fast = head;while(fast !=NULL&&fast->next !=NULL) { slow =slow->next; fast =fast->next->next; } // reverse the second half of the list ListNode* second =reverse(slow); ListNode* first = head; // construct the new list by interleaving two halveswhile(first !=NULL&& second !=NULL) { ListNode* tmp =first->next;first->next = second; first = tmp; tmp =second->next;second->next = first; second = tmp; }if(first !=NULL)first->next =NULL; }private:ListNode*reverse(ListNode* head) { ListNode* prev =NULL;while(head !=NULL) { ListNode* next =head->next;head->next = prev; prev = head; head = next; }return prev; }};
Runtime: 44 ms, faster than 95.04% of C++ online submissions for Reorder List. Memory Usage: 12.1 MB, less than 88.24% of C++ online submissions for Reorder List.