题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
利用最小堆
用 priority_queue 创建最小堆,遍历原链表,将每个结点的值 push 到最小堆中,然后再将堆顶元素依次弹出并创建新链表。
/**
* 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>> pq;
while (head) {
pq.push(head->val);
head = head->next;
}
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
while (!pq.empty()) {
ListNode* new_head = new ListNode(pq.top());
cur->next = new_head;
cur = cur->next;
pq.pop();
}
return dummy->next;
}
};