链表算法之【合并两个有序链表】

目录

LeetCode-21题


LeetCode-21题

将两个升序链表合并成一个新的升序链表并返回

java 复制代码
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null)
            return list2;
        if (list2 == null)
            return list1;

        ListNode dummyHead = new ListNode();
        ListNode curr = dummyHead;
        // 双指针
        ListNode p1 = list1;
        ListNode p2 = list2;

        while (p1 != null && p2 != null) {
            // 链入节点值较小的节点
            if (p1.val < p2.val) {
                curr.next = p1;
                p1 = p1.next;
            } else {
                curr.next = p2;
                p2 = p2.next;
            }
            curr = curr.next;
        }
        
        // 处理剩余节点
        if (p1 != null)
            curr.next = p1;
        if (p2 != null)
            curr.next = p2;

        return dummyHead.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
相关推荐
864记忆1 天前
Spring Boot 项目标准目录结构
java
2301_772093561 天前
KVSTORE_Pain point_tuchuang_ROS2
java·开发语言·1024程序员节
刘火锅1 天前
Java 17 环境下 EasyPoi 反射访问异常分析与解决方案(ExcelImportUtil.importExcelMore)
java·开发语言·python
朝新_1 天前
【SpringBoot】详解Maven的操作与配置
java·spring boot·笔记·后端·spring·maven·javaee
西部风情1 天前
聊聊连续、递增
java·开发语言
Mcband1 天前
IDEA Debug高阶技巧
java·ide·intellij-idea
budingxiaomoli1 天前
算法--滑动窗口(一)
数据结构·算法
又是忙碌的一天1 天前
java字符串
java·开发语言
王哈哈^_^1 天前
【数据集】【YOLO】【目标检测】农作物病害数据集 11498 张,病害检测,YOLOv8农作物病虫害识别系统实战训推教程。
人工智能·深度学习·算法·yolo·目标检测·计算机视觉·1024程序员节
xier_ran1 天前
邻接矩阵的 k 次幂意味着什么?从图论到路径计数的直观解释
算法·图论