LeetCode Sort List
来源:互联网 发布:淘宝库存同步软件 编辑:程序博客网 时间:2024/05/22 16:50
在 O(nlogn)的时间内对一个链表进行排序。。明显是要用归并或者快排
第一次知道说原来归并也可以用链表来写,被刷了下三观。。。。。用快慢指针的方法找分界点。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:ListNode *getMid(ListNode *head){ListNode *slow=head;ListNode *fast=head;while(fast->next!=NULL&&fast->next->next!=NULL){slow=slow->next;fast=fast->next;fast=fast->next;}return slow;} ListNode *sortList(ListNode *head) { if(head==NULL||head->next==NULL) { return head; } ListNode *mid=getMid(head); ListNode *next=mid->next; mid->next=NULL; return mergeList(sortList(head),sortList(next)); } ListNode *mergeList(ListNode *a,ListNode *b) { ListNode *tmphead=new ListNode(-1); ListNode *cur=tmphead; while(a&&b) { if(a->val<=b->val) { cur->next=a; a=a->next; } else { cur->next=b; b=b->next; } cur=cur->next; } cur->next=NULL; cur->next= a==NULL?b:a; cur=tmphead->next; delete tmphead; return cur; }};
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
- Android学习之 关于内部Handler类引起内存泄露
- Python基础编程(四)字典:当索引不好用时
- mkyaffs2image工具解析
- static用法小结
- hdu 3644 A Chocolate Manufacturer's Problem(模拟退火)
- LeetCode Sort List
- 堆和栈的区别
- Ubuntu下Vim快捷操作
- cygwin 乱码解决方案
- 《软件工程导论》第五版 张海藩 编著 总结
- cocos2d-x 3.0的回调用函数
- 一个好程序员的编程修养
- 类A中使用类B的变量
- package auction.model;