学习链表的重点
题干
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
题解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
//python做法全部都死自己做出来的,而且思考和打代码时间很短,执行耗时也低;只不过,是用了把链表全部存进数组,对数组排序,再生成链表。空间复杂度比较高
//看了评论区和题解,这个最正确的解法是归并排序 merge
//链表的归并排序:1.递归实现;2.自底向上
//递归的话,会用到栈,所以空间复杂度是O(logn),不符合题意的常量级别空间复杂度
//此处采用自底向上的归并排序,参考题解中的一个c++的答案
//统计
ListNode pre = new ListNode(0);
pre.next = head; //指向头结点
ListNode p = pre.next;
//求长度
//可用快慢指针切割
int length = 0;
while (p != null){
p = p.next;
++length;
}
//循环 开始切割合并
//size是切割的长度
//这是本算法的核心部分;!!!做链表的题目一定要画图
for (int size = 1; size < length; size <<= 1){//移位操作符!记住!学会!
ListNode tail = pre;//tail用于merge时候的拼接
ListNode cur = pre.next;
while (cur != null){
ListNode left = cur;
ListNode right = cut(cur, size); //断开前半
cur = cut(right, size); //断开后半
tail.next = merge(left, right);
while(tail.next != null){
tail = tail.next;
}
}
}
return pre.next;
}
//切割该链表并返回,后半的头(参数就是前半的头)
private static ListNode cut(ListNode head, int n){
if (n <= 0) return head;
ListNode p = head;
while(--n > 0 && p != null) p = p.next;
if (p == null) return null;//退出是因为p==null的话
ListNode next = p.next;
p.next = null;
return next;
}
//合并两个列表,按从小到大的顺序
private static ListNode merge(ListNode l1, ListNode l2){
ListNode pre = new ListNode(0);
ListNode p = pre;
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 (l2 == null) p.next = l1;
if (l1 == null) p.next = l2;
return pre.next;
}
}