Leetcode 21:合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

例:

复制代码
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
java 复制代码
public class title21 {
    public static void main(String[] args) {

        int[] l1={1,2,4};
        int[] l2={1,3,4};
        ListNode list1=createList(l1);
        ListNode list2=createList(l2);

        printList(list1);
        printList(list2);

        ListNode list3=mergeTwoLists(list1,list2);
        printList(list3);

    }



    //1.创建链表
    public static ListNode createList(int[] nums){
        ListNode head=new ListNode();   //头节点
        ListNode preNode = head;
        for(int i=0;i<nums.length;i++){
            ListNode node=new ListNode(nums[i]);    //创建一个新结点
            preNode.next=node;
            preNode=node;
        }
        return head;
    }


    //2.遍历链表
    public static ListNode printList(ListNode head) {
        ListNode node = head.next;   //从头节点的下一节点开始遍历
        while (node != null) {
            System.out.print(node.val + "\t");
            node = node.next;
        }
        System.out.println();
        return head;
    }


    //3.合并两个升序链表
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode node=new ListNode(-1);
        ListNode preNode=node;
        while (list1 != null && list2 !=null ){
            if(list1.val<list2.val){
                preNode.next=list1;
                list1=list1.next;

            }else {
                preNode.next=list2;
                list2=list2.next;

            }
            preNode=preNode.next;
        }
        if(list1==null){
            preNode.next=list2;
        }
        if(list2==null){
            preNode.next=list1;
        }
        return node.next;
    }
}
相关推荐
Blossom.1182 分钟前
大模型知识蒸馏实战:从Qwen-72B到Qwen-7B的压缩艺术
大数据·人工智能·python·深度学习·算法·机器学习·pygame
海琴烟Sunshine3 小时前
leetcode 383. 赎金信 python
python·算法·leetcode
cynicme9 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员9 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
随意起个昵称9 小时前
【递归】二进制字符串中的第K位
c++·算法
mjhcsp10 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
立志成为大牛的小牛10 小时前
数据结构——四十一、分块查找(索引顺序查找)(王道408)
数据结构·学习·程序人生·考研·算法
xier_ran10 小时前
深度学习:RMSprop 优化算法详解
人工智能·深度学习·算法
地平线开发者10 小时前
不同传感器前中后融合方案简介
算法·自动驾驶
地平线开发者11 小时前
征程 6X 常见 kernel panic 问题
算法·自动驾驶