题解 | #单链表的排序#
单链表的排序
http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
sort
将结点存到vector中,利用sort函数进行排序,排序后重新连接各节点即可
C++代码:
class Solution {
public:
ListNode* sortInList(ListNode* head) {
vector<ListNode *> a;
while (head) {
a.push_back(head);
head = head->next;
}
sort(a.begin(), a.end(), cmp);
for (int i = 0; i < a.size() - 1; i++) {
a[i]->next = a[i + 1];
}
a[a.size() - 1]->next = NULL;
return a[0];
}
static bool cmp (ListNode *a, ListNode *b) {
return a->val < b->val;
}
};