Skip to content

21. Merge Two Sorted Lists

难度:Easy

刷题内容

原题连接

  • https://leetcode.com/problems/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:

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

解题方案

思路 **- 时间复杂度: O(N + M)*- 空间复杂度: O(1)***

首先这两个链表是排序好的,那么我们先定义一个空链表,再定义两个指针 i,j,按照顺序比较两个链表,如果 i 指向的数字小于 j指向的数字,i 指向的节点插入新链表中,i = i -> next,反之则操作 j。不过要注意其中一个链表可能会先结束,所以另一个未结束的链表直接插入新链表即可

/**
 * 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* h1 = l1;
        ListNode* h2 = l2;
        ListNode* t = new ListNode(0);
        ListNode* curr = t;
        while (h1 && h2)
        {
            if (h1->val <= h2->val) {
                curr->next = h1; 
                h1 = h1->next;
            }
            else{
                curr->next = h2;
                h2 = h2->next;
            }
            curr = curr->next;
        }
        while (h1)
        {
            curr->next = h1;
            h1 = h1->next;
            curr = curr->next;
        }
        while(h2)
        {
            curr->next = h2;
            h2 = h2->next;
            curr = curr->next;
        }
        ListNode* res = t->next;
        delete t;
        return res;
    }
};


回到顶部