力扣21:合并两个有序链表

题目

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例 1:
在这里插入图片描述

输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]

示例 2:

输入:l1 = [], l2 = []
输出:[]

示例 3:

输入:l1 = [], l2 = [0]
输出:[0]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/merge-two-sorted-lists

思路

首先考虑两种特殊情况,一种是list1为空,直接返回list2,还有一种是list2为空,返回list1即可(其实这种也包含了如果两者都为空,返回空)。

最后考虑list1与list2都不为空,这个时候我们可以创建一个新的链表,node作为该链表的头结点,而temp一直为当前结点,最终成为了一个尾节点。

当list2的值大于等于list1的时候,将list1的节点加入到新链表中,即temp.next—>list1,list1后移,新链表temp也后移。

当list2的值小于list1的时候,将list2的节点加入到新链表中,即temp.next—>list2,list2后移,新链表temp也后移。

如果这个时候list1为空了,也就是后面没有结点了,就不用比较了,直接将新链表指向list2,返回头结点的下一个结点。如果是list2为空了,也就是后面没有结点了,也不用比较了,直接将新链表指向list1,返回头结点的下一个结点。

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

当提交的时候显示超出时间限制

改进

class Solution {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode node = new ListNode(0);
        ListNode temp = node;
        while (list1 != null && list2 != null){
            if (list2.val >= list1.val){
                temp.next = list1;
                list1 = list1.next;
                temp = temp.next;
            }else{
                temp.next = list2;
                list2 = list2.next;
                temp = temp.next;
            }
        }
        if (list1 == null){
            temp.next = list2;
        }else{
            temp.next = list1;
        }
        return node.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值