Algorithms—148.Sort List
2015-09-22 12:25
621 查看
思路:归并排序。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head==null||head.next==null) {
return head;
}
ListNode mid=getMid(head);
ListNode next=mid.next;
mid.next=null;
return merge(sortList(head),sortList(next));
}
public ListNode getMid(ListNode head){
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null&&fast.next.next!=null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode merge(ListNode a,ListNode b){
ListNode ans=new ListNode(0);
ListNode node=ans;
while (a!=null&&b!=null) {
if (a.val<b.val) {
node.next=a;
a=a.next;
}else {
node.next=b;
b=b.next;
}
node=node.next;
}
node.next=a==null?b:a;
return ans.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if (head==null||head.next==null) {
return head;
}
ListNode mid=getMid(head);
ListNode next=mid.next;
mid.next=null;
return merge(sortList(head),sortList(next));
}
public ListNode getMid(ListNode head){
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null&&fast.next.next!=null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode merge(ListNode a,ListNode b){
ListNode ans=new ListNode(0);
ListNode node=ans;
while (a!=null&&b!=null) {
if (a.val<b.val) {
node.next=a;
a=a.next;
}else {
node.next=b;
b=b.next;
}
node=node.next;
}
node.next=a==null?b:a;
return ans.next;
}
}
相关文章推荐
- Django搭建简单网页的学习笔记 之三(View)
- martini框架源码阅读分析
- Django搭建简单网页的学习笔记 之一(models)
- Ubuntu安装sougou输入法
- 【学习笔记】Google glog 使用
- New world,Good luck!
- golang(够烂)的helloworld
- Django 通用视图
- Django class based view walkthrough: TemplateView
- Django 1.6 最佳实践: 如何正确使用 CBVs (Class-based views)
- Google浏览器如何加载本地文件
- Django学习中的问题总结
- 【2016去哪儿网笔试题】找出输入中有几个死锁
- boost的字符串处理函数——string algorithm
- Django block extends include区别
- go语言遍历目录中的文件
- django 1.8 官方文档翻译:7-2 管理操作
- Google APAC 2016 University Graduates Test Round B解题报告
- google如何恢复误删除书签
- Django(1)Tango with Django过程中的问题