题解 | #牛的品种排序IV#
牛的品种排序IV
https://www.nowcoder.com/practice/bd828af269cd493c86cc915389b02b9f
创建优先级队列,将每个节点放入优先级队列中,然后依次弹出每个节点组合成链表返回。
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <queue> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ ListNode* sortCowsIV(ListNode* head) { // write code here priority_queue<ListNode*, vector<ListNode*>, Compare> pri_queue; ListNode* current = head; while(current != nullptr) { pri_queue.push(current); current = current->next; } head = pri_queue.top(); pri_queue.pop(); current = head; while(pri_queue.size() != 0) { current->next = pri_queue.top(); pri_queue.pop(); current = current->next; if(pri_queue.size() == 0) { current->next = nullptr; } } return head; } struct Compare { bool operator()(ListNode* a, ListNode* b) { return a->val > b->val; } }; };
较难(算法题解) 文章被收录于专栏
较难难度题目