剑指Offer II 077、链表排序
方法一、归并排序
首先对链表进行拆分,分成两部分,然后分别对两部分进行排序,最后使用merge对排好序的两部分进行排序,返回merge的排序结果。
- 链表节点为偶数或者为奇数,都可以用slow.next作为当前链表的中点,使用下面的代码找到链表的中点:
while(quick.next != null) {
if(quick.next.next != null) {
slow = slow.next;
quick = quick.next.next;
}else{
break;
}
}
- 把原来的链表根据中点分为两部分
quick = slow.next;
slow.next = null;
- 继续调用归并算法,最后对排好序的before和after进行merge并返回
/**
* 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) {
if(head == null || head.next == null) return head;
ListNode slow = head;
ListNode quick = head;
while(quick.next != null) {
if(quick.next.next != null) {
slow = slow.next;
quick = quick.next.next;
}else{
break;
}
}
quick = slow.next;
slow.next = null;
ListNode before = sortList(head);
ListNode after = sortList(quick);
return merge(before, after);
}
public ListNode merge(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode temp = dummy;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
temp.next = l1;
l1 = l1.next;
}else{
temp.next = l2;
l2 = l2.next;
}
temp = temp.next;
}
if(l1 != null) {
temp.next = l1;
}
if(l2 != null) {
temp.next = l2;
}
return dummy.next;
}
}