/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode mid = getMid(head);
ListNode midNext = mid.next;
mid.next = null;
return merge(sortList(head), sortList(midNext));
}
private ListNode getMid(ListNode head){
ListNode slow = head, fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode merge(ListNode l1, ListNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode result = new ListNode(Integer.MIN_VALUE);
if(l1.val < l2.val){
result = l1;
result.next = merge(l1.next, l2);
}else{
result = l2;
result.next = merge(l1, l2.next);
}
return result;
}
}
[LeetCode] 148. Sort List
最新推荐文章于 2022-09-04 18:20:54 发布