题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
  public:
    struct ListNodeCMP {
        bool operator()(ListNode* a, ListNode* b) {
            return a->val >= b->val;
        }
    };

    ListNode* sortInList(ListNode* head) {
        ListNode* myhead = nullptr;
        priority_queue<ListNode*, vector<ListNode*>, ListNodeCMP> pq;
        while (head) {
            pq.push(head);
            head = head->next;
        }
        ListNode* mytail = nullptr;
        while (!pq.empty()) {
            auto pp = pq.top();
            pq.pop();
            if (!myhead) {
                myhead = pp;
                mytail = myhead;
            } else {
                mytail->next = pp;
                mytail = mytail->next;
            }
        }
        mytail->next = nullptr;
        return myhead;
    }
};

优先队列

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务