0
点赞
收藏
分享

微信扫一扫

LeetCode 23 - 合并有序链表(困难链表)

自由情感小屋 2022-03-12 阅读 42

题目链接https://leetcode-cn.com/problems/merge-k-sorted-lists/题目:

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.


思路:

链表的操作是这道题的难点,k个链表的操作会更加困难,所以我们可以先从两个链表着手。第一种想法是先写出一个能合并两个链表的算法,然后对k个链表执行k-1次即可。空间复杂度为O(1),但时间复杂度较高O(k^{2}n)。

对于链表的操作有几点需要注意:对于会被修改的链表,需要创建一个指针来记录原链表的起始位置(或者修改的位置),否则最后可能找不到起始位置在哪里。

题解:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode *a, ListNode *b) {
        if(a==nullptr) return b;
        if(b==nullptr) return a;

        ListNode head, *tail = &head;   // "head" is the head of the answer list
        // head must be saved, therefore we have pointer tail which can be moved

        while (a && b) {
            // each time we put a new val at the tail of the answer list
            if (a->val < b->val) {
                tail->next = a; a = a->next;
            } else {
                tail->next = b; b = b->next;
            }
            tail = tail->next;
        }

        // put the remaining list to tail of the answer list
        if(a==nullptr) tail->next=b;
        else tail->next=a;

        return head.next;
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode *ans = nullptr;
        for (size_t i = 0; i < lists.size(); ++i) {
            ans = mergeTwoLists(ans, lists[i]);
        }
        return ans;
    }
};
举报

相关推荐

0 条评论