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;
        }
    }

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-24 13:39
在记录秋招的大魔王很...:别被忽悠了,我做了多年销售。我可以告诉你,这就是忽悠你的,销售一定要看底薪也要看提成两者不可缺一。提成是有业绩的时候才拿的到的,谁能保证一直有单状态都好。销售有时候很讲究运气的。底薪是你这个人这个岗位日常工作体现的价值。别小看底薪,你看那些跳槽去做经理主管的,底薪底一些,人家愿意去吗?所以那些说销售靠提成的纯属忽悠,除非他们的业务很容易成单。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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