栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

LeetCode21. 合并两个有序链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode21. 合并两个有序链表

思路

就是用另个指针来遍历两个链表,每次移动一个,把当前两个指针中值最小的数作为最后的结果。

要注意链表为空的时候。我用的是101来判断,因为题目说最大是100。

代码
class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list2 == null && list1 == null){
            return list1;
        }
        ListNode res = new ListNode();
        ListNode res1 =res;
        int l = 0;
        int r = 0;
        while(list1 != null || list2 != null){

            if(list1 == null){
                l = 101;
            }else{
                l = list1.val;
                
            }
            if(list2 == null){
                r = 101;
            }else{
                r = list2.val;
            }
            if(l==r && l==101){
                break;
            }
            
            if(l == 101){
                res1.next = new ListNode(r);
                list2 = list2.next;
            }else if(r == 101){
                res1.next = new ListNode(l);
                list1 = list1.next;
            }else if(l <= r){
                res1.next = new ListNode(l) ;
                list1 = list1.next;
            }else{
                res1.next = new ListNode(r);
                list2 = list2.next;
            }
            res1 = res1.next;
        }
        return res.next;


    }
}

方法二:

public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }
        ListNode res = new ListNode();
        ListNode temp = res;
        while(list1 != null && list2 != null){
            
            if(list1.val<=list2.val){
                temp.next = list1;
                list1 = list1.next;
            }else{
                temp.next = list2;
                list2 = list2.next;
            }
            temp = temp.next;
        }
        if(list1 == null){
                temp.next = list2;
            }
            if(list2 == null){
                temp.next = list1;
            }
        return res.next;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942242.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号