LeetCode_#21_合并两个有序链表 Merge Two Sorted Lists_C++题解

21. 合并两个有序链表 Merge Two Sorted Lists

题目描述

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

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

Example 1:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Example 2:

Input: [], []
Output: []

参考官方题解

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *result = new ListNode(-1);
        ListNode *p = result;
        while(l1 != NULL && l2 != NULL){
            if (l1->val <= l2->val){
                p->next = l1;
                l1 = l1->next;
            }
            else{
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        p->next = l1 != NULL ? l1 : l2;
        return result->next;
    }
};

注意

  • 设置一个哨兵节点可以比较容易地返回合并后的链表。
  • 循环终止时,只需要简单地将非空链表接在合并链表的后面,并返回合并链表即可。

复杂度

  • 时间复杂度:\(O(n + m)\) ,其中 n 和 m 分别为两个链表的长度。
    • 因为每次循环迭代中,l1 和 l2 只有一个元素会被放进合并链表中, 因此 while 循环的次数不会超过两个链表的长度之和。
  • 空间复杂度:\(O(1)\)

自解

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        vector<ListNode*> v;
        if (l1 == NULL && l2 == NULL) return l1;
        while(l1 != NULL && l2 != NULL){
            if (l1->val <= l2->val){
                v.push_back(l1);
                l1 = l1->next;
            }
            else{
                v.push_back(l2);
                l2 = l2->next;
            }
        }
        while(l1 != NULL){
            v.push_back(l1);
            l1 = l1->next;
        }
        while(l2 != NULL){
            v.push_back(l2);
            l2 = l2->next;
        }
        for (int i = 0; i < v.size() - 1; i++)
            v[i]->next = v[i+1];
        v[v.size()-1]->next = NULL;
        return v[0];
    }
};

做 PAT 静态链表题留下的习惯,用vector保存结点可以方便地按新链表顺序输出,但这里需要返回的是链表头结点,所以需要重新按顺序连接一遍链表,多此一举,影响效率。

posted @ 2020-05-25 22:53  鲸90830  阅读(134)  评论(0)    收藏  举报