您的位置:首页 > 其它

LintCode 链表排序

2017-03-31 10:01 435 查看
题目描述:

在 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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表