Sort a linked list in O(n log n) time using constant space complexity.
用冒泡:时间超出
用归并:成功解决
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/** TLE
class Solution {
public:
ListNode* sortList(ListNode* head) {
ListNode* list = head;
while(head!=NULL){
ListNode* p = head;
while(p->next!=NULL){
if(p->val > p->next->val)
{
int t = p->val;
p->val = p->next->val;
p->next->val = t;
}
p = p->next;
}
head = head->next;
}
return list;
}
};
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* l1= head;
ListNode* l2= head->next;
while(l2!=NULL && l2->next!=NULL)
{
l1 = l1->next;
l2 = l2->next->next;
}
l2 = l1->next;
l1->next = NULL;
return mergeTwoLists(sortList(head),sortList(l2));
}
ListNode* mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l2->next, l1);
return l2;
}
}
};
本文介绍了一种在O(n log n)时间内使用常数空间复杂度对链表进行排序的方法。通过对比冒泡排序(时间超出)和归并排序(成功解决),展示了如何有效地实现链表的归并排序算法。

被折叠的 条评论
为什么被折叠?



