排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表
思路
刚开始用冒泡排序写的,但这个排序方法时间复杂度为O(n^2),leetcode上最后三个输入样例会超时,要用其他排序方法
代码
冒泡排序
class Solution {
public:
ListNode* sortList(ListNode* head) {
int m=0;int len=1;
ListNode* h=head;
if(head==NULL){
return head;
}
while(h->next!=NULL){
h=h->next;
len++;
}
h=head;
for(int i=0;i<len;i++){
for(int j=0;j<len-1;j++){
if(h->val>h->next->val){
m=h->val;
h->val=h->next->val;
h->next->val=m;
}
h=h->next;
}
h=head;
}
return head;
}
};
归并排序(时间复杂度为O(nlogn))
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == NULL || head->next == NULL)return head;
else
{
ListNode *fast = head,*slow = head;
while(fast->next != NULL && fast->next->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
fast = slow;
slow = slow->next;
fast->next = NULL;
fast = sortList(head);
slow = sortList(slow);
return merge(fast,slow);
}
ListNode* merge(ListNode *head1, ListNode *head2){
if(head1 == NULL)return head2;
if(head2 == NULL)return head1;
ListNode* res;
ListNode* p;
if(head1->val < head2->val)
{res = head1; head1 = head1->next;}
else{res = head2; head2 = head2->next;}
p = res;
while(head1 != NULL && head2 != NULL)
{
if(head1->val < head2->val)
{
p->next = head1;
head1 = head1->next;
}
else
{
p->next = head2;
head2 = head2->next;
}
p = p->next;
}
if(head1 != NULL)p->next = head1;
else if(head2 != NULL)p->next = head2;
return res;
}
}
};