leetcode Sort List (Sort a linked list in O(n log n) time using constant space complexity)
2013-11-18 12:53
477 查看
Sort a linked list in O(n log n)
time using constant space complexity.
题目就是链表的排序。迅速回顾下排序时间在这个级别上的,发现只有归并是合适的。也就是写个链表上的归并排序吧。
对于链表上的归并,其实就是把链表断开然后重新连接上,每次从n/2处断开,分别排序后再链接起来。思路很简单,可能处理链表的时候复杂点。我就简单按照这个思路写了下一次ac。代码不难理解就直接贴代码吧。
如果有不正确的地方,请指正谢谢
time using constant space complexity.
题目就是链表的排序。迅速回顾下排序时间在这个级别上的,发现只有归并是合适的。也就是写个链表上的归并排序吧。
对于链表上的归并,其实就是把链表断开然后重新连接上,每次从n/2处断开,分别排序后再链接起来。思路很简单,可能处理链表的时候复杂点。我就简单按照这个思路写了下一次ac。代码不难理解就直接贴代码吧。
ListNode *sortList(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(!head) return NULL; int k=0; ListNode *p=head; while(p) { k++; p=p->next; } if(k==1) return head; int l=k/2; //计算结点个数,将链表分开。 p=head; ListNode *q=head,*t=NULL; for(int i=0;i<l && q ;i++) { if(i==l-1) t=q; q=q->next; } if(t) t->next=NULL;//将链表分开。 p=sortList(p);//分别对两段排序 q=sortList(q); ListNode *hd=NULL,*pp=NULL; while(p&&q)//合并 { if(p->val<=q->val) { if(!hd) pp=hd=p; else { pp->next=p; pp=p; } p=p->next; } else { if(!hd) hd=pp=q; else { pp->next=q; pp=q; } q=q->next; } } if(p) pp->next=p; if(q) pp->next=q; return hd; }
如果有不正确的地方,请指正谢谢
相关文章推荐
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- leetcode_Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity.
- leetcode Sort a linked list in O(n log n) time using constant space complexity.
- Sort a linked list in O(n log n) time using constant space complexity
- Sort_list——Sort a linked list in O(n log n) time using constant space complexity. 合并排序
- [LeetCode] 148. Sort List (Linked List) - Using Quick Sort(小改动)
- Point-in-Time (Incremental) Recovery Using the Binary Log
- Reverse a doubly linked list in O(1) time
- bubble sort in linked list....(java version)
- leetcode_Sort a linked list using insertion sort.
- Point-in-Time (Incremental) Recovery Using the Binary Log
- 【Leetcode】Sort List in O(nlogn) O(1)space
- leetcode上的Sort a linked list using insertion sort
- LeetCode234——Palindrome Linked List,O(n) time and O(1) space
- Sort a linked list using insertion sort
- Sort a linked list using insertion sort