C++ recursion with priority_queue and move semantics


  • 0
    M
    struct cmp{
        bool operator()(const ListNode *a,const ListNode *b) const {
            return b && (a==nullptr || a->val>b->val);
        }
    };
    class Solution {
        ListNode* helper(auto& lists) {
            ListNode *ans=lists.top();lists.pop();
            if(ans==nullptr) return nullptr;
            lists.push(ans->next);
            ans->next=helper(lists);
            return ans;
        }
    public:
        ListNode* mergeKLists(vector<ListNode*>& lists) {
            if(lists.empty()) return nullptr;
            priority_queue<ListNode*, vector<ListNode*>, cmp> pq{ cmp{}, std::move(lists) };
            return helper(pq);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.