Leetcode 21:合并两个有序链表

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

例:

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
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;
    }
}

相关推荐

  1. Leetcode21 合并有序

    2024-02-08 04:00:02       66 阅读
  2. Leetcode 21合并有序

    2024-02-08 04:00:02       60 阅读
  3. [leetcode] 21. 合并有序

    2024-02-08 04:00:02       45 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-08 04:00:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-08 04:00:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-08 04:00:02       82 阅读
  4. Python语言-面向对象

    2024-02-08 04:00:02       91 阅读

热门阅读

  1. Linux 设置自动挂载磁盘

    2024-02-08 04:00:02       57 阅读
  2. vue百度地图的和element输入框/v-region的联动

    2024-02-08 04:00:02       54 阅读
  3. 2024/2/7

    2024-02-08 04:00:02       53 阅读
  4. mysql学习打卡day24

    2024-02-08 04:00:02       55 阅读
  5. 大数据概念与术语简介

    2024-02-08 04:00:02       41 阅读
  6. 谈谈mybatis的理解(三)

    2024-02-08 04:00:02       51 阅读
  7. vim最简单命令学习

    2024-02-08 04:00:02       61 阅读
  8. 开源软件的未来发展趋势

    2024-02-08 04:00:02       55 阅读