【数据结构入门_链表】 Leetcode 21. 合并两个有序链表

原题连接: Leetcode 21. Merge Two Sorted Lists

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:
在这里插入图片描述

Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

Input: list1 = [], list2 = []
Output: []

Example 3:

Input: list1 = [], list2 = [0]
Output: [0]

Constraints:

  • The number of nodes in both lists is in the range [0, 50].
  • -100 <= Node.val <= 100
  • Both list1 and list2 are sorted in non-decreasing order.

方法一:迭代

思路:

先建立一个虚拟头结点prehead,和一个指向虚拟头结点的指针prev。返回的时候返回prehead->head就可以,能减少很多麻烦的边界问题。
两个指针遍历两个链表。每次选择关键字小的结点接到prev上即可。
注意最后需要扫尾,把循环结束没遍历完的链表的余下部分直接接上去。
这个扫尾的思想用的太多了,类似于归并排序

c++代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        // 创建虚拟头结点prehead, 值为-1    prev为指向虚拟头结点的指针
        ListNode* preHead = new ListNode(-1);
        ListNode* prev = preHead;

        // 双指针遍历两个链表
        while(list1 != nullptr && list2 != nullptr){
            // 找到小的结点
            if(list1->val < list2->val){
                prev->next = list1;
                list1 = list1->next;
            } else {
                prev->next = list2;
                list2 = list2->next;
            }
            prev = prev->next;
        }
        
        // 扫尾
         prev->next = (list1 == nullptr ? list2 : list1);

        return preHead->next;
    }
};

复杂度分析:

  • 时间复杂度:O(m+n),需要遍历两个链表的所有元素
  • 空间复杂度:O(1),常数个临时变量
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值