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;
    }

}
相关推荐
q***25116 小时前
Spring Boot 集成 Kettle
java·spring boot·后端
筱顾大牛16 小时前
IDEA使用Gitee来创建远程仓库
java·gitee·intellij-idea
懂得节能嘛.16 小时前
【SDK开发实践】从Java编码到阿里云制品仓库部署
java·阿里云·maven
空空kkk16 小时前
SpringMVC——异常
java·前端·javascript
重整旗鼓~17 小时前
1.大模型使用
java·语言模型·langchain
sino爱学习17 小时前
FastUtil 高性能集合最佳实践:让你的 Java 程序真正“快”起来
java·后端
.豆鲨包17 小时前
【Android】 View事件分发机制源码分析
android·java
-森屿安年-17 小时前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
北京地铁1号线17 小时前
数据结构:堆
java·数据结构·算法
百***864617 小时前
Spring Boot应用关闭分析
java·spring boot·后端