Java算法每日一题

题目描述

将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例:输入:l1 = 1,2,4, l2 = 1,3,4输出:1,1,2,3,4,4

解题思路
  • 递归法:比较两个链表的头节点,取较小的节点作为当前节点,然后递归合并剩余节点;
  • 迭代法(推荐):用虚拟头节点简化边界处理,遍历两个链表,依次拼接较小的节点。
Java 代码(迭代法)
复制代码
// 定义链表节点
class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class MergeTwoLists {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        // 虚拟头节点,简化链表拼接
        ListNode dummy = new ListNode(-1);
        ListNode curr = dummy;
        
        // 遍历两个链表,直到其中一个为空
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                curr.next = list1;
                list1 = list1.next;
            } else {
                curr.next = list2;
                list2 = list2.next;
            }
            curr = curr.next;
        }
        
        // 拼接剩余的节点(其中一个链表可能还有未遍历的节点)
        curr.next = list1 == null ? list2 : list1;
        
        return dummy.next;
    }

    // 测试用例:打印链表
    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    public static void main(String[] args) {
        // 构建链表1: 1->2->4
        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        // 构建链表2: 1->3->4
        ListNode l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        
        MergeTwoLists solution = new MergeTwoLists();
        ListNode result = solution.mergeTwoLists(l1, l2);
        // 输出:1 1 2 3 4 4
        printList(result);
    }
}
答案解析
  • 虚拟头节点dummy的作用:避免处理 "头节点为空" 的边界情况;
  • 时间复杂度:O (m+n)(m、n 为两个链表长度),空间复杂度:O (1)。
相关推荐
「QT(C++)开发工程师」5 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天5 小时前
0 初识C++
开发语言·c++
FfHUCisI6 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI6 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
秋饼6 小时前
JDK 27 企业级 AI 服务落地实战:G1 默认、紧凑对象头、后量子 TLS 与 JFR 脱敏全解析
java·ai·技术分享·后端开发
Asize7 小时前
146. LRU 缓存
算法
Asize7 小时前
543. 二叉树的直径
算法
卓怡学长7 小时前
w176基于SpringBoot的医院管理系统
java·spring boot·spring·maven·intellij-idea
lemon_sjdk7 小时前
ObjectProperty
java·开发语言·算法