leetcode-sort-list 发表于 2017-03-04 | 题目大意 https://leetcode.com/problems/sort-list/ 单链表排序,要求时间复杂度O(n*logn),空间复杂度:O(1) 题目分析 先利用快慢指针找到链表中点,然后每段递归调用,最后merge两个链表 代码12345678910111213141516171819202122232425262728293031323334353637383940414243444546public class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { // 这里注意head.next == null的判断 return head; } ListNode slow = head; ListNode fast = head; ListNode pre = null; while (fast != null) { fast = fast.next; if (fast != null) { fast = fast.next; } pre = slow; slow = slow.next; } ListNode p1 = sortList(slow); pre.next = null; ListNode p2 = sortList(head); // merge two sorted linked list ListNode newHead = new ListNode(-1); ListNode cur = newHead; while (p1 != null || p2 != null) { if (p1 == null) { cur.next = p2; break; } if (p2 == null) { cur.next = p1; break; } if (p1.val < p2.val) { cur.next = p1; p1 = p1.next; } else { cur.next = p2; p2 = p2.next; } cur = cur.next; } return newHead.next; }}