LeetCode 21. 合并两个有序链表

21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

Input: list1 = [1,2,4], list2 = [1,3,4]

Output:[1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []

Output: []

Example 3:

**Input:**list1 = [], list2 = [0]

Output:[0]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

解法思路:

1、递归

2、迭代

法一:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // Recursion
        // Time: O(m+n)
        // Space: O(m+n)
        if (list1 == null) {
            return list2;
        } else if (list2 == null) {
            return list1;
        } else if (list1.val < list2.val){
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }
    }
}

法二:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // Iterator double pointer
        // Time: O(m+n)
        // Space: O(1)
        ListNode dummyNode = new ListNode(0);
        ListNode cur = dummyNode;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        cur.next = list1 != null ? list1 : list2;
        return dummyNode.next;
    }
}
相关推荐
lightqjx4 分钟前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
Wave8451 小时前
数据结构—树
数据结构
ic爱吃蓝莓1 小时前
数据结构 | HashMap原理
数据结构·学习·算法·链表·哈希算法
add45a1 小时前
C++编译期数据结构
开发语言·c++·算法
灰色小旋风1 小时前
力扣21 合并两个有序链表(C++)
c++·leetcode·链表
2401_891482172 小时前
C++模块化编程指南
开发语言·c++·算法
沉鱼.442 小时前
树、堆的题目集
算法
暮冬-  Gentle°2 小时前
自定义类型转换机制
开发语言·c++·算法
2301_816651222 小时前
嵌入式C++低功耗设计
开发语言·c++·算法
机器学习之心2 小时前
PSO-LightGBM-ABKDE粒子群算法优化轻量级梯度提升机自适应带宽核密度估计多变量回归区间预测Matlab实现
算法·matlab·回归·abkde·自适应带宽核密度估计·pso-lightgbm·粒子群算法优化轻量级梯度提升机