首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >合并两个排序的链表_16

合并两个排序的链表_16

作者头像
名字是乱打的
发布2021-12-23 18:12:01
发布2021-12-23 18:12:01
67000
代码可运行
举报
文章被收录于专栏:软件工程软件工程
运行总次数:0
代码可运行

上代码:

代码语言:javascript
代码运行次数:0
运行
复制
 public ListNode Merge(ListNode list1,ListNode list2) {
        if (list1==null){
            return list2;
        }
        if (list2==null){
            return list1;
        }

        ListNode head=null;
        ListNode curr=null;
        while (list1!=null||list2!=null){
            if (list1==null){
                while (list2!=null){
                    curr.next=list2;
                    curr=list2;
                    list2=list2.next;
                }
                return head;
            }
            if (list2==null){
                while (list1!=null){
                    curr.next=list1;
                    curr=list1;
                    list1=list1.next;
                }
                return head;
            }
            //1 2 8 9 10
            //2 5 5 7 8
            if (list1.val<= list2.val){
                if (head==null){
                    head=list1;
                    curr=head;
                }else {
                    curr.next=list1;
                    curr=list1;
                }
                list1=list1.next;
            }else {
                if (head==null){
                    head=list2;
                    curr=head;
                }else {
                    curr.next=list2;
                    curr=list2;
                }
                list2=list2.next;
            }
        }
        return head;
    }

这是第一版本的;思路,如果遍历过程中有一个集合为空了,那么就把另外一个链表里的结点都添加到新链表里,实际上我们这个时候可以直接把另外一个不为空的链表直接加在我们新链表后面了

上代码:

代码语言:javascript
代码运行次数:0
运行
复制
public ListNode Merge(ListNode list1,ListNode list2) {
        if (list1==null){
            return list2;
        }
        if (list2==null){
            return list1;
        }

        ListNode head=null;
        ListNode curr=null;
        while (list1!=null&&list2!=null){
            if (list1.val<= list2.val){
                if (head==null){
                    head=list1;
                    curr=head;
                }else {
                    curr.next=list1;
                    curr=list1;
                }
                list1=list1.next;
            }else {
                if (head==null){
                    head=list2;
                    curr=head;
                }else {
                    curr.next=list2;
                    curr=list2;
                }
                list2=list2.next;
            }
        }
        if (list1==null){
            curr.next=list2;
        }else {
            curr.next=list1;
        }
        return head;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/3/28 下,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档