Leetcode--Sort List
来源:互联网 发布:万人网络营销软件站 编辑:程序博客网 时间:2024/06/15 21:35
Problem Description:
Sort a linked list in O(n log n) time using constant space complexity.
分析:对链表进行排序,思考排序算法时间复杂度为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,*r=NULL,*newhead=NULL; while(q&&q->next!=NULL) { r=p; p=p->next; q=q->next->next; } q=r->next;//找到另一半的起始节点 r->next=NULL; p=head; p=sortList(p); q=sortList(q); if(p&&q) { if(p->val<=q->val)//先初始化头结点 { newhead=r=p; p=p->next; } else { newhead=r=q; q=q->next; } //merge p and q while(p&&q) { if(p->val<=q->val) { r->next=p; r=p; p=p->next; } else { r->next=q; r=q; q=q->next; } } } if(p) r->next=p; if(q) r->next=q; return newhead; }};
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
- BJOI2014 2014.8.13
- 01.策略模式 【STRATEGY PATTERN】
- Uva 6177
- HDU 2206 IP的计算
- JNI 笔记 (总结一些基础的,常用的)
- Leetcode--Sort List
- VB.net 控制Excel添加Sheet页,指定添加位置
- 【140814】VC++ 数据库编程教程 pdf 高清电子书
- 文件处理
- 更不接口
- makefile的语法及写法
- qt4嵌入式开发环境搭建过程(包括各种异常问题)(2)
- 关于C++程序键盘输入文件结束符
- 七、数据管理与碰撞检测