LeetCode 21Merge Two Sorted Lists 合并两个排序链表 Java

**题目:**将两个已排序的链表合并在一起。

举例1:

输入:list1 = [1,2,4], list2 = [1,3,4];

输出:[1,1,2,3,4,4];

举例2:

输入:list1 = [] , list2 = [];

输出:[]

举例3:

输入: list1 = [] , list2 = [0];

输出: [0]

**解题思路:**遍历两个链表,比较节点值来合并链表,当其中一个链表遍历完成时,将另一个链表剩余部分拼入新链表。

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) {
        ListNode head = new ListNode(0);
        ListNode currect = head;

        //比较节点,获取较小节点拼入
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                currect.next = list1;
                list1 = list1.next;
            } else {
                currect.next = list2;
                list2 = list2.next;
            }
            currect = currect.next;
        }

        //若其中一个链表已遍历完成,拼入另一个链表到新链表中
        if (list1 == null) {
            currect.next = list2;
        } else {
            currect.next = list1;
        }

        return head.next;
    }

}
相关推荐
月夕·花晨3 分钟前
Gateway-过滤器
java·分布式·spring·spring cloud·微服务·gateway·sentinel
hssfscv1 小时前
JAVA学习笔记——9道综合练习习题+二维数组
java·笔记·学习
初听于你3 小时前
缓存技术揭秘
java·运维·服务器·开发语言·spring·缓存
小蒜学长4 小时前
springboot多功能智能手机阅读APP设计与实现(代码+数据库+LW)
java·spring boot·后端·智能手机
zizisuo7 小时前
解决在使用Lombok时maven install 找不到符号的问题
java·数据库·maven
笨蛋少年派7 小时前
JAVA基础语法
java·开发语言
dragoooon347 小时前
[优选算法专题三.二分查找——NO.24搜索旋转排序数组中的最⼩值]
数据结构·leetcode·动态规划
Haooog7 小时前
654.最大二叉树(二叉树算法)
java·数据结构·算法·leetcode·二叉树
我真的是大笨蛋7 小时前
依赖倒置原则(DIP)
java·设计模式·性能优化·依赖倒置原则·设计规范
Swift社区7 小时前
LeetCode 392 判断子序列
算法·leetcode·职场和发展