在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
(偷懒了)
/**
* 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) {
for(ListNode *w=head;w;w=w->next)
for(ListNode *e=w->next;e;e=e->next)
{
if (w->val>e->val)
{
int t=w->val;
w->val=e->val;
e->val=t;
}
}
return head;
}
};