欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Merge k Sorted Lists 合并k个有序链表

程序员文章站 2024-03-22 11:28:31
...
  1. #include
    #include
    #include
    #include
    #include
    #include
    using namespace std;
    struct ListNode
    {
    int val;
    ListNode *next;
    ListNode(int val, ListNode next = nullptr)
    {
    this->val = val;
    this->next = next;
    }
    };
    ListNode
    mergeTwoLists(ListNode l1, ListNode l2)
    {
    ListNode *dummy = new ListNode(-1), *cur = dummy;
    while (l1 && l2)
    {
    if (l1->val < l2->val)
    {
    cur->next = l1;
    l1->next = cur;
    }
    else
    {
    cur->next = l2;
    l2->next = cur;
    }
    cur = cur->next;
    }
    if (l1) cur->next = l1;
    if (l2) cur->next = l2;
    return dummy->next;
    }
    ListNode mergeKList(vector<ListNode> &lists)
    {
    if (lists.empty())
    {
    return nullptr;
    }
    int n = lists.size();
    while (n < 1)
    {
    int k = (n+1) / 2;
    for (int i = 0; i < n / 2; i++)
    {
    lists[i] = mergeTwoLists(lists[i], lists[i + k]);
    }
    n = k;
    }
    return lists[0];
    }
    struct cmp
    {
    bool operator()(ListNode x, ListNode y)
    {
    return x->val > y->val;
    }
    };
    ListNode mergeKList(vector<ListNode> &lists)
    {
    priority_queue<ListNode
    , vector<ListNode
    >, cmp> qcmp;
    for (ListNode *node : lists)
    {
    qcmp.push(node);
    }
    ListNode *dummy = new ListNode(-1), *cur = dummy;
    while (!qcmp.empty())
    {
    ListNode *node = qcmp.top();
    qcmp.pop();

    cur->next = node;
    cur = cur->next;
    if (cur->next) qcmp.push(cur->next);
    

    }
    return dummy->next;
    }
    int main()
    {

    system(“pause”);
    return 0;
    }

相关标签: 合并链表