给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]

示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]

示例 3:
输入:head = []
输出:[]
思路:使用快慢指针,截断节点
class Solution {
public ListNode sortList(ListNode head) {
if (head == null) {
return head;
}
if (head.next == null) {
return head;
}
ListNode slow = head;
ListNode quick = head;
while (quick.next != null && quick.next.next != null) {
slow = slow.next;
quick = quick.next.next;
}
ListNode next = slow.next;
slow.next = null;
ListNode l1 = sortList(head);
ListNode l2 =sortList(next);
ListNode listNode = mergeTwoLists(l1, l2);
return listNode;
}
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode(1);
ListNode cur = head;
ListNode cur1 = list1;
ListNode cur2 = list2;
while (cur1 != null && cur2 != null) {
if (cur1.val > cur2.val) {
cur.next = new ListNode(cur2.val);
cur = cur.next;
cur2 = cur2.next;
} else if (cur1.val < cur2.val) {
cur.next = new ListNode(cur1.val);
cur = cur.next;
cur1 = cur1.next;
} else {
cur.next = new ListNode(cur1.val);
cur.next.next = new ListNode(cur2.val);
cur = cur.next.next;
cur1 = cur1.next;
cur2 = cur2.next;
}
}
while (cur1 != null) {
cur.next = cur1;
cur = cur.next;
cur1 = cur1.next;
}
while (cur2 != null) {
cur.next = cur2;
cur = cur.next;
cur2 = cur2.next;
}
if (head.next != null) {
head = head.next;
} else {
head = null;
}
return head;
}
}