Sort List
Sort a linked list in O(n log n) time using constant space complexity.
 

需要采用归并排序对链表进行操作。
 
归并排序思想:每次选取链表中间元素,把链表分割成两部分,
递归分割,直到链表中的元素是有序的时候(即只有一个元素时候),这时对链表进行合并,
合并的时候,每次选两个链表中小的元素放在下一个位置。
 
 
 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public: ListNode *mergeList(ListNode *h1,ListNode *h2)
{
ListNode *head=new ListNode();
ListNode *cur=head;
while(h1!=NULL&&h2!=NULL)
{
if(h1->val>h2->val)
{
cur->next=h2;
h2=h2->next;
}
else
{
cur->next=h1;
h1=h1->next;
} cur=cur->next;
} cur->next=h1==NULL?h2:h1; cur=head;
head=head->next;
delete cur; return head;
} ListNode *sortList(ListNode *head) { if(head==NULL||head->next==NULL) return head; ListNode *slow,*fast;
slow=fast=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
} ListNode *mid=slow->next;
slow->next=NULL; ListNode *h1=sortList(head);
ListNode *h2=sortList(mid);
return mergeList(h1,h2); }
};

最新文章

  1. linux基础快速掌握课件
  2. JS编码解码
  3. [ZigBee] 10、ZigBee之睡眠定时器
  4. native2ascii 国际资源文件编码
  5. 屠蛟之路_重登数据库大山_SecondDay
  6. ScrollView与TableView实现选择效果
  7. php笔记03:布尔类型,字符串,浮点数
  8. xxx is not in the sudoers file.This incident will be reported.的解决方法
  9. 使用alloctor模板来实现string类
  10. js 中的switch
  11. 增删查改-MySQL
  12. 7-21(排序) PAT排名汇总
  13. nginx常用场景
  14. [CSAcademy]Find the Tree
  15. en-zh(科学技术)science and technology-2
  16. Titanic缺失数值处理 & 存活率预测
  17. input[type="checkbox"]与label对齐
  18. yum使用过程中的常见错误
  19. 【DevExpress v17.2新功能预告】DevExtreme ASP.NET MVC新的强类型HTML Helpers
  20. mongo转换副本集

热门文章

  1. java在目录中过滤文件
  2. grunt使用watch和livereload的Gruntfile.js的配置
  3. jquery 插件之 点赞“+1” 特效
  4. Myeclipse报PermGen space异常的问题
  5. POJ2823 Sliding Window
  6. [IOS UIalert模版]
  7. TCP/IP详解 笔记一
  8. appium按钮定位,去掉弹出框
  9. ActivityInfo taskAffinity
  10. 让VisualVM+BTrace进入unsafe mode