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;
    }
}
相关推荐
心中有国也有家7 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事7 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院7 小时前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet8 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
m0_6294947311 小时前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户11 小时前
用队列实现栈
数据结构·算法
做人求其滴11 小时前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣
daad77711 小时前
记一组无人机IMU传感器数据
算法
计算机安禾11 小时前
【c++面向对象编程】第42篇:模板特化与偏特化:为特定类型定制实现
开发语言·c++·算法