148. 排序链表-中等-链表、归并排序
给你链表的头结点head
,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在O(n log n)
时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目在范围
[0, 5 * 104]
内 -105 <= Node.val <= 105
题解
链表的归并排序,使用了递归方法,希望再碰到链表的归并问题能做出来
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
public ListNode sortList(ListNode head, ListNode tail){
if(head == null){
return head;
}
// 非常关键的一步,切割链表
if(head.next == tail){
head.next = null;
return head;
}
// 使用双指针切割链表,一个一次走一步,一个走两步
ListNode t1 = head, t2 = head;
while(t2 != tail){
t1 = t1.next;
t2 = t2.next;
if(t2 != tail){
t2 = t2.next;
}
}
// 默认tail不算节点,也不参与
ListNode L1 = sortList(head, t1);
ListNode L2 = sortList(t1, tail);
// 合并两个有序链表
return Merge(L1, L2);
}
public ListNode Merge(ListNode L1, ListNode L2){
ListNode dummyHead = new ListNode(0);
ListNode t1 = L1, t2 = L2, t = dummyHead;
while(t1 != null && t2 != null){
if(t1.val <= t2.val){
t.next = t1;
t1 = t1.next;
}else{
t.next = t2;
t2 = t2.next;
}
t = t.next;
}
if(t1 != null){
t.next = t1;
}
if(t2 != null){
t.next = t2;
}
return dummyHead.next;
}
}