NC70 单链表的排序
描述
给定一个无序单链表,实现单链表的排序(按升序排序)。
示例1
输入:
[1,3,2,4,5]
复制
返回值:
{1,2,3,4,5}
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
if(head == null || head.next == null){
return head ;
}
ListNode mid = findMid(head) ;
ListNode right = sortInList(mid.next) ;
mid.next = null ;
ListNode left = sortInList(head) ;
return merge(left , right) ;
}
public ListNode findMid(ListNode head){
ListNode slow = head , fast = head.next ;
while(fast != null && fast.next != null){
slow = slow.next ;
fast = fast.next.next ;
}
return slow ;
}
public ListNode merge(ListNode head1 , ListNode head2){
ListNode dummy = new ListNode(0);
ListNode tail = dummy ;
while(head1 != null && head2 != null){
if(head1.val > head2.val){
tail.next = head2 ;
head2 = head2.next ;
}else{
tail.next = head1 ;
head1 = head1.next ;
}
tail = tail.next ;
}
if(head1 != null){
tail.next = head1 ;
}
if(head2 != null){
tail.next = head2 ;
}
return dummy.next ;
}
}