题解 | #priority_queue(堆)单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        // write code here
        priority_queue<int, vector<int>, greater<int> > heap; 
        ListNode *p = head;
	  //把链表中的元素全部压入小根堆,
        while (p) {
            heap.push(p->val);
            p=p->next;
        }
        ListNode *ymm = new ListNode(-1);
        p = ymm;
        while (!heap.empty()) {
            ListNode *temp = new ListNode(heap.top());
            heap.pop();
            p->next = temp;
            p=temp;
        }
        return ymm->next;
    }
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-20 14:14
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务