题目描述:
在O(n log n)的时间内使用常数级空间复杂度对链表进行排序。
示例:

解题思路:
归并排序运用在链表上(由于链表不能索引访问,故快排桶排并不合适),
拆链表使用:快慢指针
里面的几个步骤都是难点:
1.自底向上思想;
2.断链
3.归并
4.合链
代码:
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode sortList (ListNode head) {
// write code here
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode preSlow = head;
ListNode slow = head;
ListNode fast = head;
while (slow != null && fast != null && fast.next != null) {
preSlow = slow;
slow = slow.next;
fast = fast.next.next;
}
ListNode listA = head;
ListNode listB = slow;
preSlow.next = null;
listA = sortList(listA);
listB = sortList(listB);
return merge(listA, listB);
}
private ListNode merge (ListNode listA, ListNode listB) {
ListNode dummy = new ListNode(0);
ListNode nodeA = listA;
ListNode nodeB = listB;
ListNode nodeR = dummy;
while (nodeA != null && nodeB != null) {
if (nodeA.val < nodeB.val) {
nodeR.next = nodeA;
nodeA = nodeA.next;
}
else {
nodeR.next = nodeB;
nodeB = nodeB.next;
}
nodeR = nodeR.next;
}
if (nodeA != null) {
nodeR.next = nodeA;
}
if (nodeB != null) {
nodeR.next = nodeB;
}
return dummy.next;
}
}
这篇博客介绍了如何在O(n log n)的时间复杂度和常数级空间复杂度下对链表进行排序。博主详细解析了问题背景,并给出了具体的解题思路及实现代码。
268

被折叠的 条评论
为什么被折叠?



