题目描述
给定一个无序单链表,实现单链表的排序(按升序排序)。
示例
输入:head = [4,2,1,3]
输出:[1,2,3,4]
解决方法一:
时间复杂度:O(nlogn)
空间复杂度:O(logn)
归并排序(递归)
- 首先用快慢指针找到链表的中点
- 对链表进行分割
- 对链表进行合并(合并两个有序链表)
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) {
/*
1. 用快慢指针找到链表中点
2. 分割链表
3. 借助两个链表合并思想,对链表进行合并
*/
if (head == null || head.next == null) {
return head;
}
ListNode slow = head;
ListNode fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode rightNode = slow.next;
slow.next = null;
ListNode left = sortInList(head); //分割前半段
ListNode right = sortInList(rightNode); //分割后半段
return