inch using constant space complexity.
The time complexity requirement of this problem is O (n logn), it is very easy to think of the solution with MergeSort.
/*** Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution { Publiclistnode Merge (ListNode head1, ListNode head2) {ListNode dummy=NewListNode (-1); ListNode Tail=dummy; while(Head1! =NULL&& head2! =NULL){ if(Head1.val <head2.val) {Tail.next=Head1; Head1=Head1.next; } Else{Tail.next=head2; Head2=Head2.next; } Tail=Tail.next; } if(Head1! =NULL) {Tail.next=Head1; } if(Head2! =NULL) {Tail.next=head2; } returnDummy.next; } PublicListNode Findmid (ListNode head) {ListNode slow=Head; ListNode Fast= Head.next;//instead of = head to ensure slow are in the mid position while(Fast! =NULL&& Fast.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; } returnslow; } PublicListNode sortlist (ListNode head) {if(Head = =NULL|| Head.next = =NULL){ returnHead; } ListNode Mid=Findmid (head); ListNode Right=sortlist (Mid.next); Mid.next=NULL; ListNode Left=Sortlist (head); returnmerge (Left,right); } }
It is worth noting that the
1. In the merge function, dummy the pre-node and tail,
2. and findmin ListNode fast = head.next role,
function of Mid.next = NULL in 3.sortList
Leetcode-sort List