题目:
Sort a linked list in O(n log n) time using constant space complexity.
思路:
题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。
归并排序的一般步骤为:
1)将待排序数组(链表)取中点并一分为二;
2)递归地对左半部分进行归并排序;
3)递归地对右半部分进行归并排序;
4)将两个半部分进行合并(merge),得到结果。
代码:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode sortList(ListNode head) { if(head == null || head.next == null){ return head; } ListNode fast = head.next; ListNode slow = head; while (fast!=null && fast.next!=null){ slow = slow.next; fast = fast.next.next; } ListNode right = sortList(slow.next); slow.next = null; ListNode left = sortList(head); //合并两个排序好的链表 ListNode tempHead = new ListNode(0); ListNode tempNode = tempHead; while (left!=null && right!=null){ if(left.val<right.val){ tempNode.next = left; left = left.next; } else{ tempNode.next = right; right = right.next; } tempNode = tempNode.next; if(left != null){ tempNode.next = left; } if(right != null){ tempNode.next = right; } } return tempHead.next; } }