2018-08-11 23:50:30

问题描述:

问题求解:

解法一、归并排序

    public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode prev = null, slow = head, fast = head;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
return merge(l1, l2);
} private ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
}
else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if (l1 != null) {
p.next = l1;
}
if (l2 != null) {
p.next = l2;
}
return dummy.next;
}

解法二、快速排序

  public ListNode sortList(ListNode head) {
if (head == null || head.next == null)
return head;
qsort(head, null);
return head;
} // [begin, end)
void qsort(ListNode begin, ListNode end) {
if (begin == end || begin.next == end) return;
ListNode mid = partition(begin, end);
qsort(begin, mid);
qsort(mid.next, end);
} ListNode partition(ListNode begin, ListNode end) {
int key = begin.val;
ListNode p = begin;
ListNode q = begin.next;
while (q != end) {
if (q.val < key) {
p = p.next;
int tmp = p.val;
p.val = q.val;
q.val = tmp;
}
q = q.next;
}
int tmp = p.val;
p.val = begin.val;
begin.val = tmp;
return p;
}

最新文章

  1. JavaScript 函数参数传递到底是值传递还是引用传递
  2. robots.txt文件配置和使用方法详解
  3. jsonp调用webapi和mvc
  4. web.xml基本配置描述
  5. python语言学习3 ——第一个python程序
  6. 企业建站http://www.douco.com/
  7. C++ 智能指针 auto_ptr 和 shared_ptr
  8. scrapy入门使用
  9. The listener supports no services
  10. [摘录] 图灵机与lambda演算的关系
  11. windows下解决python输出utf-8中文
  12. 有关https有的网站可以访问有的访问不了的问题
  13. Android中使用隐藏API(大量图解)
  14. LinuxI/O 性能分析
  15. jQuery实现鼠标划过展示大图的方法
  16. java编写binder服务实例
  17. java 多线程 day13 condition 线程通信
  18. MongoDB day02
  19. NGUI动态字体的使用
  20. ROS机器人程序设计

热门文章

  1. 跑道标识和那些复杂的灯光系统 and 简介、编号、参数、标志及数量 and 飞机跑道标准与参数
  2. 基于Axis1.4的webservice接口开发(环境搭建)
  3. 浅谈为什么一个java源文件中只能有一个public类?
  4. Linux服务器---配置apache支持用户认证
  5. Spring Boot 踩坑之路之 Configuration Annotation Proessor not found in classpath
  6. MySQL之表连接(内外连接和重命名的使用)
  7. python百分号%—%s、%d、%f
  8. JavaScript实现表单验证
  9. 定制django admin页面的跳转
  10. python 线程 进程 协程 学习