• 算法-链表-合并两个升序链表


    描述

    输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
    数据范围: 0 \le n \le 10000≤n≤1000,-1000 \le 节点值 \le 1000−1000≤节点值≤1000
    要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)

    如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:

    在这里插入图片描述

    或输入{-1,2,4},{1,3,4}时,合并后的链表为{-1,1,2,3,4,4},所以对应的输出为{-1,1,2,3,4,4},转换过程如下图所示:
    在这里插入图片描述

    示例1
    输入:
    {1,3,5},{2,4,6}
    复制
    返回值:
    {1,2,3,4,5,6}
    复制
    示例2
    输入:
    {},{}
    复制
    返回值:
    {}
    复制
    示例3
    输入:
    {-1,2,4},{1,3,4}
    复制
    返回值:
    {-1,1,2,3,4,4}

    题解

    每个节点两两比较大小-注意某个链表为空的情况
    我的写法是:

    public class Solution {
        
        public ListNode Merge(ListNode cur_1,ListNode cur_2) {
            ListNode tempNode=new ListNode(-1);
            ListNode result=tempNode;
            while(cur_1!=null&&cur_2!=null){  
                if(cur_1.val<=cur_2.val){
                    tempNode.next=cur_1;
                    cur_1=cur_1.next;
                }else{
                    tempNode.next=cur_2;
                    cur_2=cur_2.next;
                }
                 tempNode=tempNode.next;
            }
            if(cur_1==null){
                tempNode.next=cur_2;
            }
            if(cur_2==null){
               tempNode.next=cur_1; 
            }
            
            return result.next;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    还有大佬用递归做出了,膜拜,实在没想到
    大佬代码

    public class Solution {
        public ListNode Merge(ListNode list1,ListNode list2) {
            if(list1==null){
                return list2;
            }
            else if(list2==null){
                return list1;
            }
            if(list2.val>list1.val){
                list1.next = Merge(list1.next,list2);
                return list1;
            }
            else{
                list2.next = Merge(list1,list2.next);
                return list2;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
  • 相关阅读:
    遍历的几种方式
    四非保研之旅
    Windows提权
    “中心扩展算法”思想求解回文子串问题
    怎么给视频去水印?手把手教你去水印
    消息驱动 —— SpringCloud Stream
    软件设计模式系列之一——设计模式概述
    作为高级架构师,你居然看不透大型网站技术架构的核心问题?
    QAnything部署Mac m1环境
    js事件循环与macro&micro任务队列-前端面试进阶
  • 原文地址:https://blog.csdn.net/u011212112/article/details/126074487