【LeetCode】21-合併兩個有序鏈表

合併兩個有序鏈表

題目

將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

解法1:迭代法

  • 解題思路
    需要注意的是,題目給的兩個鏈表都是有序鏈表,因此同時遍歷兩個鏈表,逐一比較即可。當其中一個鏈表遍歷完成時,另一個鏈表剩下的元素一定是大於當前鏈表的,將剩下的節點拼接到返回鏈表的尾部。

  • 代碼

class Solution {
     /**
     * 迭代法
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // new一個虛擬頭節點,這樣while中就不需要再判斷head是否爲空
        ListNode head = new ListNode(0);
        ListNode node = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            } else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        // l1或l2中較大的那個鏈表可能還有剩餘
        node.next = l1 != null ? l1 : l2;
        return head.next;
    }
}

遞歸法

  • 解題思路
    思路與迭代法相似,只是實現方法不同。

  • 代碼

class Solution {
     /**
      * 迭歸法
      */
     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;
         }
     }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章