题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
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) return null;
if(head.next == null) return head; //排除空链表 和只有一个Node的链表的情况
ListNode pre = head;
ListNode slow = head;
ListNode fast = head;
while(fast!=null&&fast.next!=null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null; //将链表从中间一分为二
ListNode head1 = sortInList(head);
ListNode head2 = sortInList(slow);
return mergeSortList(head1,head2);
}
public ListNode mergeSortList(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if(list1 == null){
cur.next = list2;
}
if(list2 == null){
cur.next = list1;
}
return dummy.next;
}
}
