天达云 科技型企业
|
亚太互联网络信息中心(APNIC)成员
|
注册免费体验
[
加载中...
] - [
免费注册
]
|
用户中心
|
在线充值
|
投诉举报
首页
域名注册
云虚拟主机
云服务器
网站模板
网站制作
渠道合作
帮助中心
天达云首页
>
互联网学习教程
>
编程语言
> 单链表快速排序
单链表快速排序
更新:HHH 时间:2023-1-7
点击(
此处
)折叠或打开
public
class
LinkedListSortTest
{
//bubble up
public
static
ListNode sortList
(
ListNode head
)
{
ListNode m
=
head
;
ListNode tail
=
null
;
while
(
m
!
=
tail
&
&
m
.
next
!
=
null
)
{
ListNode n
=
head
;
while
(
n
.
next
!
=
null
)
{
if
(
n
.
next
.
val
<
n
.
val
)
{
swap
(
n
,
n
.
next
)
;
}
n
=
n
.
next
;
}
tail
=
n
;
m
=
m
.
next
;
}
return
head
;
}
//quick sort
public
static
ListNode sortList2
(
ListNode head
)
{
ListNode
next
=
head
.
next
;
if
(
next
=
=
null
)
{
// 1 element
return
head
;
}
else
if
(
next
.
next
=
=
null
)
{
// 2 elements
if
(
head
.
val
>
next
.
val
)
{
swap
(
head
,
next
)
;
}
return
head
;
}
else
{
ListNode mid
=
getMidNode
(
head
)
;
return
merge
(
sortList
(
head
)
,
sortList
(
mid
)
)
;
}
}
private
static
ListNode merge
(
ListNode m
,
ListNode n
)
{
// System.out.println("Merge " + m + " with " + n);
ListNode head
=
new
ListNode
(
0
)
;
ListNode tail
=
head
;
while
(
m
!
=
null
&
&
n
!
=
null
)
{
if
(
m
.
val
<
n
.
val
)
{
tail
.
next
=
m
;
m
=
m
.
next
;
}
else
{
tail
.
next
=
n
;
n
=
n
.
next
;
}
tail
=
tail
.
next
;
}
if
(
m
!
=
null
)
{
tail
.
next
=
m
;
}
if
(
n
!
=
null
)
{
tail
.
next
=
n
;
}
// System.out.println("Merge result : " + head.next);
return
head
.
next
;
}
private
static
ListNode getMidNode
(
ListNode n
)
{
ListNode fast
=
n
;
ListNode slow
=
n
;
while
(
true
)
{
if
(
fast
.
next
!
=
null
)
{
fast
=
fast
.
next
;
if
(
fast
.
next
!
=
null
)
{
fast
=
fast
.
next
;
slow
=
slow
.
next
;
continue
;
}
}
break
;
}
ListNode mid
=
slow
.
next
;
slow
.
next
=
null
;
return
mid
;
}
private
static
void
swap
(
ListNode n
,
ListNode m
)
{
int
v
=
n
.
val
;
n
.
val
=
m
.
val
;
m
.
val
=
v
;
}
public
static
void
main
(
String
[
]
args
)
{
ListNode head
=
new
ListNode
(
0
)
;
int
i
=
0
;
ListNode n
=
head
;
while
(
i
+
+
<
20
)
{
n
.
next
=
new
ListNode
(
i
*
37
%
50
)
;
// n.next = new ListNode(i);
n
=
n
.
next
;
}
print
(
head
)
;
print
(
sortList
(
head
)
)
;
print
(
sortList2
(
head
)
)
;
}
public
static
void
print
(
ListNode n
)
{
while
(
n
!
=
null
)
{
System
.
out
.
print
(
n
.
val
+
" "
)
;
n
=
n
.
next
;
}
System
.
out
.
println
(
)
;
}
}
class
ListNode
{
int
val
;
ListNode
next
;
ListNode
(
int
x
)
{
val
=
x
;
}
public
String
toString
(
)
{
ListNode n
=
this
;
StringBuilder
sb
=
new
StringBuilder
(
"["
)
;
while
(
n
!
=
null
)
{
sb
.
append
(
n
.
val
+
" "
)
;
n
=
n
.
next
;
}
sb
.
deleteCharAt
(
sb
.
length
(
)
-
1
)
;
sb
.
append
(
"]"
)
;
return
sb
.
toString
(
)
;
}
}
来源于 https://leetcode.com/problems/sort-list/
148. Sort List
Sort a linked list in
O
(
n
log
n
) time using constant space complexity.
返回编程语言教程...
新手上路
全站内容搜索
互联网教程
域名购买流程
域名解析方法
产品管理
域名解析管理
云虚拟主机管理
数据库 . 管理
云服务器. 管理
支付方式
在线支付
付款方式
银联付款
发票开具
关于我们
关于我们
公司资质
代理加盟
代理登录
400-805-1963
7 * 24小时全天全国服务热线400电话