题目描述
在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
Sort a linked list in O(n log n) time using constant space complexity.
解题思路
新建一个头指针,然后不断将原链表中的结点移动到新链表中并排好序。
(ps:这个方法感觉不太像是nlogn够的)
/**
* 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) {
ListNode *res = new ListNode(0);
if(head == NULL)
return res->next;
ListNode *p, *t, *pre;
while(head){
t = head;
pre = res;
p = res->next;
while( p && p->val < t->val){
pre = p;
p = p->next;
}
head = head->next;
t->next = p;
pre->next = t;
}
return res->next;
}
};