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;
    }
}
相关推荐
m0_547486666 分钟前
《数据结构与算法(Python语言版)》全套PPT课件2026
数据结构·算法
个 人 练 习 生37 分钟前
数据结构入门:算法复杂度
开发语言·数据结构·经验分享·学习·程序人生·算法
Ricardo-Yang42 分钟前
无人机单目深度估计测试:ZipDepth 与 AerialMetric
人工智能·算法·机器学习·计算机视觉·无人机
Nil2081 小时前
golang解决单词转换
算法
imaol11 小时前
文件编程--标准IO
linux·运维·算法
青 春 记 忆1 小时前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
stolentime2 小时前
AT_agc066_a [AGC066A] Adjacent Difference题解
c++·算法·贪心算法·构造
渣波2 小时前
深度解析:LeetCode 51. N 皇后 —— 回溯算法的巅峰之作
算法
咪饭只吃一小碗2 小时前
# C++ STL 常用容器方法全面总结vector / map / set / unordered_map / unordered_set
算法
daad7772 小时前
802.11 前导码与 STF 深度解析(含检测算法与 5G 对比
人工智能·算法·5g·wifi·802.11·前导码