JZ16-合并两个排序的链表

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

/**
     * 迭代
     */
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            if (list2 == null) {
                return null;
            }
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode dummy = new ListNode(-1);
        ListNode tempEnd = dummy;

        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                tempEnd.next = list1;
                list1 = list1.next;  //看list1的下一位和list2的该位谁大,继续while
            } else {
                tempEnd.next = list2;
                list2 = list2.next;  //同理
            }
            tempEnd = tempEnd.next;  //一个循环,插入一位,end后移一位
        }

        if (list1 != null) {  //如果list1的数量较多,则直接接在后面。此时剩余的首位一点比原本的末尾要大
            tempEnd.next = list1;
        }
        if (list2 != null) {  //同理
            tempEnd.next = list2;
        }
        return dummy.next;
    }

    /**
     * 递归  把比当前大的数中的最小的赋给当前的下一位  不用细想
     */
    public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if (list1 == null) {
            if (list2 == null) {
                return null;
            }
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        if (list1.val <= list2.val) {
            list1.next = mergeTwoLists2(list1.next, list2);  //如果list1小于list2,则让list1的下一位继续比。然后将更小的赋给list1.next
            return list1;
        } else {
            list2.next = mergeTwoLists2(list1, list2.next);
            return list2;
        }
    }

全部评论

相关推荐

叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务