题解 |归并排序 #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
/**
合并有序链表
*/
public ListNode merge(ListNode p1, ListNode p2){
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
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;
}
if(p2 != null){
cur.next = p2;
}
return dummy.next;
}
public ListNode sortInList (ListNode head) {
// write code here
if(head == null || head.next == null){
return head;
}
//一:分割环节。使用快慢指针寻找链表中点,如果是偶数,则fast走到终点时,slow位于中间偏左
ListNode fast = head.next;
ListNode slow = head;
while(fast != null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//在中点处将链表一分为二
ListNode tmp = slow.next;
slow.next = null;
//二:合并环节。递归进行左右两边的排序
ListNode left = sortInList(head);
ListNode right = sortInList(tmp);
return merge(left,right);
}
}
