Sort a linked list inO(NLogN) Time using constant space complexity.
Question: You can sort a linked list by merging. There are three main parts:
1. Find the midpoint and return the findmiddle function;
2. Merge function merge;
3. sortlist.
The findmiddle function of the array is very easy to implement, and the linked list has a little tricky. First, set two pointers, one slow is initialized as head, And the other fast is initialized as head. next, then slow takes one step at a time, and fast takes two steps at a time, so when fast reaches the end point, slow will just reach the midpoint.
The merge function is very simple, that is, compare the size of the two linked list header nodes each time and put the smaller ones behind the new linked list.
Sortlist is a recursive function that recursively sorts the elements between [Head, mid] and [Mid. Next, tail] and merges them.
The Code is as follows:
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * }10 * }11 */12 public class Solution {13 private ListNode findMiddle(ListNode head){14 ListNode slow = head;15 ListNode fast = head.next;16 while(fast != null && fast.next != null){17 slow = slow.next;18 fast = fast.next.next;19 }20 return slow;21 }22 private ListNode merge(ListNode head1,ListNode head2){23 if(null == head1)24 return head2;25 if(null == head2)26 return head1;27 ListNode head;28 if(head1.val > head2.val){29 head = head2;30 head2 = head2.next;31 }32 else{33 head = head1;34 head1 = head1.next;35 }36 ListNode tail = head;37 while(head1 != null && head2 != null){38 if(head1.val > head2.val){39 tail.next = head2;40 head2 = head2.next;41 }42 else{43 tail.next = head1;44 head1 = head1.next;45 }46 tail = tail.next;47 }48 if(head1 != null)49 tail.next = head1;50 if(head2 != null)51 tail.next = head2;52 return head;53 }54 public ListNode sortList(ListNode head) {55 if(head == null || head.next == null)56 return head;57 ListNode mid = findMiddle(head);58 ListNode right = sortList(mid.next);59 mid.next = null;60 ListNode left = sortList(head);61 62 return merge(left,right);63 }64 }
On everyone's page, you can find a website that collects leetcode answers: http://answer.ninechapter.com/. it is said that the answers provided by engineers such as googleand facebookcan be learned.