leetcode:Sort List
来源:互联网 发布:信贷员靠谱抢单软件 编辑:程序博客网 时间:2024/05/29 18:31
使用常数空间的单链接排序算法,算法时间复杂度为O(nlogn),首先想到是的就是快速排序和二路归并排序,二路归并排序的实现比较简单,代码如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *sortList(ListNode *head) { if(!head || !head->next ) return head; ListNode *p=head, *q=head, *pre=NULL; while(p&&p->next){ p=p->next->next; pre=q; q=q->next; } pre->next=NULL; return meger(sortList(head),sortList(q)); } ListNode *meger(ListNode *lh, ListNode *rh){ ListNode *tmp=new ListNode(0); ListNode *p=tmp; while(lh&&rh) { if(lh->val<=rh->val) { p->next=lh; lh=lh->next; } else{ p->next=rh; rh=rh->next; } p=p->next; } if(!lh) p->next=rh; else p->next=lh; p=tmp->next; tmp->next=NULL; delete tmp; return p; }};
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
- NSRunLoop
- 与你,预约一个来生的相逢
- 黑马程序员------面向对象
- ReportStudio入门教程(二十) - 值提示的自动提交
- Visual Studio debug 模式和 release 模式
- leetcode:Sort List
- 设计的成长
- java中的断点下载文件
- C++ 将一个文件里面的相同的一个字符串替换成另一个字符串
- Cubietruck开发板SPL阶段的printf重定向问题
- 第五周作业(第四章)
- JS不定长度探究和填充占位符的应用
- 我们还在一起
- hdu3068+hdu3294 最长回文字符串的manacher算法