1. 程式人生 > 實用技巧 >LeetCode143 重排連結串列

LeetCode143 重排連結串列

給定一個單鏈表L:L0→L1→…→Ln-1→Ln ,
將其重新排列後變為: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

可以遍歷然後存起來,然後空間換時間。

也可以遞迴,但是遞迴的方法需要巧妙一點。

這裡借用windliang的解法,每次往內遞迴,把head指向tail,tail指向內部處理完的連結串列的第一個節點。

 1 public void reorderList(ListNode head) {
2 3 if (head == null || head.next == null || head.next.next == null) { 4 return; 5 } 6 int len = 0; 7 ListNode h = head; 8 //求出節點數 9 while (h != null) { 10 len++; 11 h = h.next; 12 } 13 14 reorderListHelper(head, len); 15 } 16 17 private
ListNode reorderListHelper(ListNode head, int len) { 18 if (len == 1) { 19 ListNode outTail = head.next; 20 head.next = null; 21 return outTail; 22 } 23 if (len == 2) { 24 ListNode outTail = head.next.next; 25 head.next.next = null; 26 return
outTail; 27 } 28 //得到對應的尾節點,並且將頭結點和尾節點之間的連結串列通過遞迴處理 29 ListNode tail = reorderListHelper(head.next, len - 2); 30 ListNode subHead = head.next;//中間連結串列的頭結點 31 head.next = tail; 32 ListNode outTail = tail.next; //上一層 head 對應的 tail 33 tail.next = subHead; 34 return outTail; 35 } 36 37 作者:windliang 38 連結:https://leetcode-cn.com/problems/reorder-list/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-34/ 39 來源:力扣(LeetCode) 40 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。

第三種方法就是先拆分連結串列成兩半,然後把後半部分翻轉,然後兩個連結串列合併。