leetcode 148排序链表

优先队列容器,使用小顶堆排序;timeO(nlogn) spaceO(n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        struct cmp{
            bool operator()(ListNode* a, ListNode* b){
                return a->val > b->val;
            }
        };
        priority_queue<ListNode*,vector<ListNode*>,cmp> q;
        ListNode  *pre,*cur,*ahead;
        ahead=pre=new ListNode(-1);
        
        while(head!=NULL){
            q.push(head);
            head=head->next;
        }
        while(!q.empty()){
            cur=q.top();
            pre->next=cur;
            pre=cur;
            pre->next=NULL;
            q.pop();
        }
        return ahead->next;
    }
};
原文地址:https://www.cnblogs.com/joelwang/p/11017415.html