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;
    }
}
相关推荐
laocooon5238578865 小时前
大数的阶乘 C语言
java·数据结构·算法
Boop_wu6 小时前
[Java EE] 多线程 -- 初阶(1)
java·jvm·算法
陌路206 小时前
Linux33 网络编程-多线程TCP并发
网络·算法
星释13 小时前
Rust 练习册 :Pythagorean Triplet与数学算法
开发语言·算法·rust
星释13 小时前
Rust 练习册 :Nth Prime与素数算法
开发语言·算法·rust
多喝开水少熬夜14 小时前
Trie树相关算法题java实现
java·开发语言·算法
WBluuue14 小时前
数据结构与算法:树上倍增与LCA
数据结构·c++·算法
bruk_spp15 小时前
牛客网华为在线编程题
算法
lkbhua莱克瓦2415 小时前
Java基础——集合进阶用到的数据结构知识点1
java·数据结构·笔记·github
杨福瑞15 小时前
数据结构:单链表(2)
c语言·开发语言·数据结构