49 合并两个排序链表(Merge Two Sorted Lists)

1 题目

题目:合并两个排序链表(Merge Two Sorted Lists)
描述:将两个排序(升序)链表合并为一个新的升序排序链表。

lintcode题号——165,难度——easy

样例1:

输入: list1 = null, list2 = 0->3->3->null
输出: 0->3->3->null

样例2:

输入:  list1 =  1->3->8->11->15->null, list2 = 2->null
输出: 1->2->3->8->11->15->null

2 解决方案

2.1 思路

  对有序链表的合并,从两个链表头开始,对比两个链表的表头,将较小的放入新链表,然后较小的表头向后移动,以此类推直到其中一个为空,再将剩下不空的链表直接连接在新链表的尾部即可完成排序。

2.2 时间复杂度

  若两个链表的长度分别为m和n,时间复杂度为O(m + n)。

2.3空间复杂度

  空间复杂度为O(1)。

3 源码

细节:

  1. 对比两个表头,将较小的放入新链表,直到其中一个为空。
  2. 最后将不空的链表直接连接到新链表尾部即可。

链表的拼接不需要使用循环,直接将两个链表头尾相接即可完成拼接。

C++版本:

/**
* Definition of singly-linked-list:
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*     ListNode(int val) {
*        this->val = val;
*        this->next = NULL;
*     }
* }
*/
/**
* @param l1: ListNode l1 is the head of the linked list
* @param l2: ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
    // write your code here
    if (l1 == nullptr)
    {
        return l2;
    }
    if (l2 == nullptr)
    {
        return l1;
    }

    ListNode dummyNode(0);
    ListNode * cur = &dummyNode;
    while (l1 != nullptr && l2 != nullptr)
    {
        if (l1->val < l2->val)
        {
            cur->next = l1;
            cur = cur->next;
            l1 = l1->next;
        }
        else
        {
            cur->next = l2;
            cur = cur->next;
            l2 = l2->next;
        }
    }

    // 链表拼接不需要使用循环,直接给next指针赋值即可
    if (l1 != nullptr)
    {
        cur->next = l1;
    }
    if (l2 != nullptr)
    {
        cur->next = l2;
    }

    return dummyNode.next;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值