据说要用归并方法,分而治之:
head :左边 mid:右边
将链表分为两部分,左边和右边,先找到中间节点,对左边和右边有序数列进行排序,将最新的链表
2 1 || 0 4
/ \
2 || 1 0 || 4
/ \ / \
2 1 0 4
\ / \ /
1 2 0 4
\ /
0 1 2 4
import java.util.*;
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode mid = midList(head);
ListNode midNext = mid.next;
mid.next = null; //将链表分为两个链表
return merge(sortList(head), sortList(midNext));
}
//快慢指针寻找中间节点
public ListNode midList(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode dulPtr = head;
ListNode sigPtr = head;
while(dulPtr.next != null && dulPtr.next.next != null){
dulPtr = dulPtr.next.next;
sigPtr = sigPtr.next;
}
return sigPtr;
}
//合并两个有序链表
public ListNode merge(ListNode q1, ListNode q2){
ListNode head = new ListNode(0);
ListNode cur = head;
while(q1 != null && q2 != null){
//若q1小于q2,把q1的当前节点加入队列,q1取为下一个节点
if(q1.val < q2.val){
cur.next = q1;
cur = cur.next;
q1 = q1.next;
}else{
cur.next = q2;
cur = cur.next;
q2 = q2.next;
}
}
if(q1 == null){
cur.next = q2;
}else{
cur.next = q1;
}
return head.next;
}
}