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;
    }
}
相关推荐
晴天的雨.9925 分钟前
[C++算法]快乐数
数据结构·c++·算法
孤狼warrior9 分钟前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo
影视飓风TIM11 分钟前
C++11 核心新特性完整梳理
数据结构·c++·算法
晴天的雨.99212 分钟前
[C++]算法双指针 复写0
数据结构·c++·算法
橘子汽水16827 分钟前
Leetcode 128,49最长连续序列,字母异位词分组
java·算法·leetcode
圣保罗的大教堂29 分钟前
leetcode 1140. 石子游戏 II 中等
leetcode
mmmmath_329 分钟前
LeetCode.438.找到字符串中所有字母异位词
数据结构·算法·leetcode
Nil20834 分钟前
leetcode 22括号生成
算法·leetcode·深度优先
Navigator_Z38 分钟前
LeetCode //C - 1237. Find Positive Integer Solution for a Given Equation
c语言·算法·leetcode