1.代码
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode mid = middleNode(head);
ListNode rightNode = mid.next;
mid.next = null;
ListNode left = sortList(head);
ListNode right = sortList(rightNode);
return merge(left, right);
}
public ListNode middleNode(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode merge(ListNode head1, ListNode head2) {
ListNode p1 = head1;
ListNode p2 = head2;
ListNode dummyNode = new ListNode(-1);
ListNode cur = dummyNode;
while (p1 != null && p2 != null) {
if (p1.val <= p2.val) {
cur.next = p1;
p1 = p1.next;
} else {
cur.next = p2;
p2 = p2.next;
}
cur = cur.next;
}
if (p1 != null) {
cur.next = p1;
} else if (p2 != null) {
cur.next = p2;
}
return dummyNode.next;
}
}