题目描述1 单链表排序问题
Sort a linked list in O(n log n) time using constant space complexity.
用归并排序: 其中只是创建了一个preHead节点 占用空间O(1) 时间O(nlogn)
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
} //常规合并排序思路
ListNode mid = getMid(head);
ListNode midNext = mid.next;
mid.next = null; //一定记得断开head 左半部分的链表尾部
return mergeSort(sortList(head), sortList(midNext));
}
private ListNode getMid(ListNode head) { //使用快慢指针获取中间节点位置
if(head == null || head.next == null) {
return head;
}
ListNode slow = head, quick = head;
while(quick.next != null && quick.next.next != null) {
slow = slow.next;
quick = quick.next.next;
}
return slow;
}
private ListNode mergeSort(ListNode n1, ListNode n2) { 对两个分链表进行合并
ListNode preHead = new ListNode(0), cur1 = n1, cur2 = n2, cur = preHead;
while(cur1 != null && cur2 != null) {
if(cur1.val < cur2.val) {
cur.next = cur1;
cur1 = cur1.next;
} else {
cur.next = cur2;
cur2 = cur2.next;
}
cur = cur.next;
}
cur.next = cur1 == null ? cur2 : cur1; //看哪个链表不为空 继续接上
return preHead.next;
}
}用快速排序:
public class Solution {
public ListNode sortList(ListNode head) {
quickSort(head, null);
return head;
}
public static void quickSort(ListNode head, ListNode end) {
if(head != end) {
ListNode partion = partion(head,end);
quickSort(head, partion);
quickSort(partion.next, end);
}
}
public static ListNode partion(ListNode head, ListNode end) {
ListNode slow = head;
ListNode fast = head.next;
while (fast != end) {
if(fast.val < head.val) {
slow = slow.next;
int temp=slow.val; //交换slow和fast的值
slow.val=fast.val;
fast.val=temp;
}
fast = fast.next;
}
int temp=head.val; //交换slow和最初基准值
head.val=slow.val;
slow.val=temp;
return slow;
}
}
本文介绍了一种在O(n log n)时间内使用常数空间复杂度对单链表进行排序的方法。通过归并排序和快速排序两种算法实现,并详细解释了每种方法的具体步骤。
1328

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



