题目描述:
在 O(n log n) 时间复杂度和常数级的空间复杂度下给链表排序。
样例
给出 1->3->2->null,给它排序变成 1->2->3->null.
思路分析:
sort扫一遍~
ac代码:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: You should return the head of the sorted linked list,
using constant space complexity.
*/
ListNode *sortList(ListNode *head) {
// write your code here
int a[1000005];
int top=0;
while(head!=NULL)
{
a[top++]=head->val;
head=head->next;
}
sort(a,a+top);
ListNode *dummy,*r,*s;
dummy=new ListNode(0);
r=dummy;
for(int i=0;i<top;i++)
{
s=new ListNode(a[i]);
r->next=s;
r=s;
}
return dummy->next;
}
};