Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
解題思路:
用棧將整個鏈表存儲,然後將棧頂元素插入到棧底元素的後面,循環多少次呢?鏈表
的長度除2即可.
解題代碼:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode *head) { stackstk; ListNode *tmp = head; int cnt = 0 ; while(tmp) { stk.push(tmp); tmp = tmp->next; ++cnt; } tmp = head ; for(int i = 1 ; i <= cnt / 2 ; ++i) { ListNode *tmp1 = stk.top(); stk.pop(); tmp1->next = tmp->next ; tmp->next = tmp1 ; tmp = tmp1->next; } if(head) tmp->next = NULL ; } };
注:上述代碼的空間復雜度是O(n),不過這題應該可以做到O(1)的空間的,遍歷鏈表從中間分割即可.