Scribbling

[C++] Priority Queue with custom data type 본문

Computer Science/C++

[C++] Priority Queue with custom data type

focalpoint 2024. 2. 22. 01:38

https://leetcode.com/problems/merge-k-sorted-lists/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

using namespace std;


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) {}
};


struct ListNodeComparator {
	int operator()(ListNode* node1, ListNode* node2) {
		return node1->val > node2->val;
        // return node2->val - node1->val;
	}
};


class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode* ret = new ListNode();
		ListNode* cur = ret;
		priority_queue<ListNode*, vector<ListNode*>, ListNodeComparator> pq;
		for (ListNode* node : lists) {
            if (node != nullptr) pq.push(node);
		}
		while (not pq.empty()) {
            ListNode* node = pq.top();
			cur->next = node;
            pq.pop();
			cur = node;
			if (node->next != nullptr) {
				pq.push(node->next);
			}
		}
		return ret->next;
    }
};

 

With Lambda: (C++20)

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode* ret = new ListNode();
		ListNode* cur = ret;
        auto comp = [](ListNode* node1, ListNode* node2) {
            return node1->val > node2->val;
        };
		priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq;
		for (ListNode* node : lists) {
            if (node != nullptr) pq.push(node);
		}
		while (not pq.empty()) {
            ListNode* node = pq.top();
			cur->next = node;
            pq.pop();
			cur = node;
			if (node->next != nullptr) {
				pq.push(node->next);
			}
		}
		return ret->next;
    }
};

 

'Computer Science > C++' 카테고리의 다른 글

[C++] Abstract Class, Interface, Multiple Inheritance  (0) 2024.02.14
[C++] lower_bound  (0) 2024.02.06
[C++] Deque<int>  (0) 2024.02.06
[C++] 전문가를 위한 C++ - Chapter 8  (0) 2023.10.07
[C++] find, deque, bfs, structured binding  (0) 2023.09.30