力扣hot100 合并两个有序链表 递归 双指针

Problem: 21. 合并两个有序链表
在这里插入图片描述

💖 递归

思路

👨‍🏫 参考地址
在这里插入图片描述

n , m n,m n,m 分别为 list1 和 list2 的元素个数
⏰ 时间复杂度: O ( n + m ) O(n+m) O(n+m)
🌎 空间复杂度: O ( n + m ) O(n+m) O(n+m)

/**
 * 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)
	{
		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;
		}
	}
}

💖 双指针

👨‍🏫 参考地址
在这里插入图片描述

⏰ 时间复杂度: O ( n + m ) O(n+m) O(n+m)
🌎 空间复杂度: O ( 1 ) O(1) O(1)

class Solution {
   
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
   
        ListNode dum = new ListNode(0), cur = dum;
        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 dum.next;
    }
}

相关推荐

  1. 经典150题第五十八题:合并有序

    2024-01-23 22:48:01       31 阅读
  2. <题海拾贝>[]2.合并有序

    2024-01-23 22:48:01       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-23 22:48:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-23 22:48:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-23 22:48:01       82 阅读
  4. Python语言-面向对象

    2024-01-23 22:48:01       91 阅读

热门阅读

  1. leetcode 2788按分隔符拆分字符串

    2024-01-23 22:48:01       58 阅读
  2. 参数校验: spring-boot-starter-validation

    2024-01-23 22:48:01       48 阅读
  3. GPT只是开始,Autonomous Agents即将到来

    2024-01-23 22:48:01       50 阅读
  4. 结构体(C语言)

    2024-01-23 22:48:01       55 阅读
  5. C++程序设计(第3版)谭浩强 第9章 习题

    2024-01-23 22:48:01       54 阅读
  6. 信息安全法律法规与国家政策(1)

    2024-01-23 22:48:01       49 阅读
  7. ip被限制怎么办

    2024-01-23 22:48:01       57 阅读