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)。
相关推荐
重生之后端学习1 小时前
114. 二叉树展开为链表
java·数据结构·算法·链表·职场和发展·深度优先
xyq20241 小时前
SQL `LAST()` 函数详解
开发语言
Lun3866buzha1 小时前
人员跌倒检测系统:基于Faster R-CNN的改进模型实现与优化_1
开发语言·r语言·cnn
csdn2015_2 小时前
mybatisplus自动生成id
java·mybatis
时艰.2 小时前
电商订单系统设计与实现
java
sheji34162 小时前
【开题答辩全过程】以 基于Java的网上书店销售系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
天一生水water2 小时前
基于FFT的频域故障诊断
人工智能·算法·智慧油田
lsx2024062 小时前
JavaScript 类继承
开发语言
listhi5202 小时前
基于C#实现动态人脸检测
开发语言·c#