147. 对链表进行插入排序
class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode last = head;
ListNode cur = head.next;
while(cur != null){
if(last.val <= cur.val){
last = last.next;
}else{
ListNode pre = dummyHead;
while(pre.next != null && pre.next.val < cur.val){
pre = pre.next;
}
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
}
cur = last.next;
}
return dummyHead.next;
}
}
148. 排序链表
class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode fast = head, slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode node = slow.next;
slow.next = null;
ListNode left = sortList(head);
ListNode right = sortList(node);
return merge(left, right);
}
public ListNode merge(ListNode left, ListNode right){
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
while(left != null && right != null){
if(left.val < right.val){
cur.next = left;
left = left.next;
}else{
cur.next = right;
right = right.next;
}
cur = cur.next;
}
if(left != null){
cur.next = left;
}
if(right != null){
cur.next = right;
}
return dummyHead.next;
}
}
- 时间复杂度 O ( n l o g n ) O(nlogn) O(nlogn),空间复杂度 O ( l o g n ) O(logn) O(logn)