题目链接:合并 K 个升序链表

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

方法一:暴力

/**
 * 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* mergeKLists(vector<ListNode*>& lists) {
        vector<int> nodes;
        for (int i = 0;i < lists.size();i++) {
            ListNode* cur = lists[i];
            while (cur != nullptr) {
                nodes.push_back(cur->val);
                cur = cur->next;
            }
        }
        sort(nodes.begin(),nodes.end());

        ListNode head(0);
        ListNode* tmp = &head;
        //tmp = nullptr;
        //head->next = tmp;
        for (int i = 0;i < nodes.size();i++) {
            tmp->next = new ListNode(nodes[i]);
            tmp = tmp->next;
        }
        return head.next;
    }
};

标签: hot100, Hard, 暴力

添加新评论