链表排序 Sort List
2024-09-22 04:31:18
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;
}
最新文章
- JavaScript 函数参数传递到底是值传递还是引用传递
- robots.txt文件配置和使用方法详解
- jsonp调用webapi和mvc
- web.xml基本配置描述
- python语言学习3 ——第一个python程序
- 企业建站http://www.douco.com/
- C++ 智能指针 auto_ptr 和 shared_ptr
- scrapy入门使用
- The listener supports no services
- [摘录] 图灵机与lambda演算的关系
- windows下解决python输出utf-8中文
- 有关https有的网站可以访问有的访问不了的问题
- Android中使用隐藏API(大量图解)
- LinuxI/O 性能分析
- jQuery实现鼠标划过展示大图的方法
- java编写binder服务实例
- java 多线程 day13 condition 线程通信
- MongoDB day02
- NGUI动态字体的使用
- ROS机器人程序设计
热门文章
- 跑道标识和那些复杂的灯光系统 and 简介、编号、参数、标志及数量 and 飞机跑道标准与参数
- 基于Axis1.4的webservice接口开发(环境搭建)
- 浅谈为什么一个java源文件中只能有一个public类?
- Linux服务器---配置apache支持用户认证
- Spring Boot 踩坑之路之 Configuration Annotation Proessor not found in classpath
- MySQL之表连接(内外连接和重命名的使用)
- python百分号%—%s、%d、%f
- JavaScript实现表单验证
- 定制django admin页面的跳转
- python 线程 进程 协程 学习