LeetCode 0021 Merge Two Sorted Lists
阿新 • • 發佈:2022-03-10
1. 題目描述
2. Solution 1
1、思路分析
類似合併兩個有序陣列,設定兩個指標分別指向兩個連結串列的head,比較大小,把較小的結點從原始連結串列摘下掛到結果連結串列中。
2、程式碼實現
package Q0099.Q0021MergeTwoSortedLists; import DataStructure.ListNode; public class Solution1 { /* 遞迴 設f(l1, l2)為遞迴功能函式 遞迴終止條件: f(l1, l2) = l2; 若 l1 == null f(l1, l2) = l1; 若 l2 == null 遞迴主體: f(l1, l2) = l1 + f(l1->next, l2); 若 l1的結點值 小於 l2的結點值 f(l1, l2) = l2 + f(l1, l2-> next); else */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null || l2 == null) return l1 != null ? l1 : l2; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } } }
3. Solution 2
1、思路分析
迭代實現
2、程式碼實現
package Q0099.Q0021MergeTwoSortedLists; import DataStructure.ListNode; public class Solution2 { // 迭代 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null || l2 == null) return l1 != null ? l1 : l2; ListNode head = new ListNode(0); // 頭結點 ListNode p = head; while (l1 != null && l2 != null) { // 進入迴圈的條件是 與,不然,把非空的連結串列掛到結果鏈 if (l1.val < l2.val) { p.next = l1; l1 = l1.next; } else { p.next = l2; l2 = l2.next; } p = p.next; } p.next = l1 != null ? l1 : l2; return head.next; } }