Sort a linked list in O(n log n) time using constant space complexity.
链表排序,要求时间复杂度O(nlgn),我写的归并排序。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode sortList(ListNode head) { if(head==null){ return head; } ListNode tail = head; while(tail.next!=null){ tail=tail.next; } return mergeList(head,tail); } ListNode mergeList(ListNode head,ListNode tail){ if(head==tail){ return head; } ListNode mid = getMid(head,tail); ListNode postList = mergeList(mid.next,tail); mid.next=null; ListNode preList = mergeList(head,mid); return merge(preList,postList); } ListNode getMid(ListNode head,ListNode tail){ if(head==tail){ return head; } ListNode fast = head,slow = head; while(fast.next!=null&&fast.next.next!=null&&fast.next!=tail){ fast=fast.next.next; slow=slow.next; } return slow; } ListNode merge(ListNode l1,ListNode l2){ if(l1==null||l2==null){ return l1==null?l2:l1; } ListNode ptr = new ListNode(0); ListNode head = ptr; while(l1!=null&&l2!=null){ if(l1.val<=l2.val){ ptr.next = l1; l1=l1.next; }else{ ptr.next = l2; l2=l2.next; } ptr=ptr.next; } ptr.next=l1==null?l2:l1; return head.next; } }