java 148.排序清单(#anki).java
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 148.排序清单(#anki).java相关的知识,希望对你有一定的参考价值。
/**
* 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 middle = findMidpoint(head);
ListNode right = sortList(middle.next);
middle.next = null;
ListNode left = sortList(head);
return merge(left,right);
}
public ListNode findMidpoint(ListNode head){
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
public ListNode merge(ListNode left, ListNode right){
ListNode dummy = new ListNode(-1);
ListNode tail = dummy;
while(left != null && right != null){
if(left.val < right.val){
tail.next = left;
left = left.next;
} else {
tail.next = right;
right = right.next;
}
tail = tail.next;
}
if (left != null){
tail.next = left;
} else {
tail.next = right;
}
return dummy.next;
}
}
以上是关于java 148.排序清单(#anki).java的主要内容,如果未能解决你的问题,请参考以下文章
java 148.排序清单(#anki).java
java 148.排序清单(#anki).java
java 148.排序清单(#anki).java
java 148.排序清单(#anki).java
java 167.两个Sum II - 输入数组被排序(#anki).java
java 167.两个Sum II - 输入数组被排序(#anki).java