K个有序链表,用一个函数合并它们,并返回最终合并的结果:

代码如下:

    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        priority_queue<Node> q;
        ListNode L(1);
        ListNode* c = &L;
        L.next = NULL;
        for (int i = 0; i < lists.size(); ++i)
        {
            if (lists[i] != NULL)
            {
                Node n;
                n.index = i;
                n.value = lists[i]->val;
                // lists[i] = lists[i]->next;
                q.push(n);
            }
        }
        while (!q.empty())
        {
            Node x = q.top();
            q.pop();
            c->next = lists[x.index];
            c = c->next;
            lists[x.index] = lists[x.index]->next;
            if (lists[x.index] != NULL)
            {
                x.value = lists[x.index]->val;
                q.push(x);
            }
        }
        c->next = NULL;
        return L.next;
    }

 

相关文章:

  • 2021-11-15
  • 2021-12-02
  • 2021-12-26
  • 2021-06-19
  • 2021-07-26
  • 2021-07-09
  • 2021-05-03
猜你喜欢
  • 2022-12-23
  • 2021-07-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-12
相关资源
相似解决方案