Sort a linked list in O(n log n) time using constant space complexity.
findMiddle: 将listnode 不停的拆分
sort: 将拆分好的不同的sort
merge: 将sort好的,向上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 mid=findMiddle(head); ListNode right=sortList(mid.next); mid.next=null; ListNode left=sortList(head); return merge(left,right); } private ListNode findMiddle(ListNode head){ ListNode slow=head; ListNode fast=head.next; while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; } return slow; } private ListNode merge(ListNode head1,ListNode head2){ ListNode result=new ListNode(0); ListNode temp=result; while(head1!=null&&head2!=null){ if(head1.val<=head2.val){ temp.next=head1; head1=head1.next; } else{ temp.next=head2; head2=head2.next; } temp=temp.next; } if(head1!=null){ temp.next=head1; } else{ temp.next=head2; } return result.next; } }
时间: 2024-11-02 00:01:25