leetcode Sort List(**)
来源:互联网 发布:淘宝小卖家还能做吗 编辑:程序博客网 时间:2024/06/05 07:25
Sort a linked list in O(n log n) time using constant space complexity.
O(nlogn)的有快速排序,归并排序,堆排序。这里需要采用归并排序。把一个链表分为等长的两个链表,对这两个链表分别进行归并排序,再将这两个链表有序合并。
class Solution {public: ListNode *sortList(ListNode *head) { if(head==NULL)return NULL; ListNode *p,*q,*hd=NULL,*temp=NULL; int n,l; n=0; p=head; while(p){ n++; p=p->next; } if(n==1)return head; l=n/2;p=head; for(int i=1;i<=l;i++){ if(i==l)temp=p; p=p->next; } temp->next=NULL; q=head; q=sortList(q); p=sortList(p); while(p&&q){ if(p->val<=q->val){ if(hd==NULL){ hd=temp=p; }else{ hd->next=p; hd=hd->next; } p=p->next; }else{ if(hd==NULL){ hd=temp=q; }else{ hd->next=q; hd=hd->next; } q=q->next; } } if(p)hd->next=p; if(q)hd->next=q; return temp; }};
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- foj 1692 矩阵快速幂&&循环矩阵优化
- Lake Countinge的s
- poj 2299
- Cocos2d-x开发实例:使用Lambda 表达式
- POJ1979 FLIP GAME (DFS&BFS都可以)
- leetcode Sort List(**)
- Ctype.h 中isdigit 函数的使用 HDU2017 字符串
- POJ1279-Art Gallery
- 阿斯顿发阿斯顿法师打发士大夫
- fsasd fsdaf dsf sd
- hdu 1588 构造矩阵
- Oracle over函数
- HDU1180 诡异的楼梯 广搜 优先队列
- Qt 二维码生成