LeetCode Tencent's selection of 50 questions - sort list

Problem-solving ideas: merge

Open the first list, divided into two parts, only one has been removed to the element, merging, using the starting position after a temporary list of node records rearrangement

The merger is not difficult, difficult point is how to split the list, his general idea is to use two hands, one at a time to move two, a mobile one, when the end of the movement fast, slow pointer position is the middle of the list position,

The intermediate position subsequent cutting recursively, and then the next pointer points to a null neutral position, i.e., open chain, and then the daughter strand is left recursive.

When the boundary condition is that the intermediate position coincides with the starting position, returns to the starting list

code show as below:

 1 package algorithm;
 2 
 3 import basic.ListNode;
 4 
 5 public class SortLinkList {
 6 
 7     public ListNode sortList(ListNode head) {
 8 
 9         return sort(head,null);
10     }
11 
12 
13     private ListNode sort(ListNode head,ListNode middle) {
14 
15         if(head == null && middle == null){
16             return null;
17         }
18         if(head == middle){
19             return head;
20         }
21         ListNode fast = head;
22         ListNode slow = head;
23         while (fast != null && fast != middle && fast.next != middle){
24             fast = fast.next.next;
25             slow = slow.next;
26         }
27 
28         ListNode subNode = slow;
29         ListNode r = sort(slow.next,middle);
30 
31         subNode.next = null;
32         ListNode l = sort(head,subNode);
33 
34         return merge(l,r);
35     }
36 
37     private ListNode merge(ListNode left ,ListNode right){
38 
39         ListNode temp = new ListNode(0);
40         ListNode record = temp;
41         while (left != null && right!= null){
42             if(left.val < right.val){
43                 record.next = left;
44                 left = left.next;
45 
46             }else {
47                 record.next = right;
48                 right = right.next;
49             }
50             record = record.next;
51         }
52         if(left != null){
53             record.next = left;
54         }else if(right!= null){
55             record.next = right;
56         }
57         return temp.next;
58     }
59 
60 
61 }

 

However, since only the O (NlogN) for recording an empty linked list node, so the space complexity is O (1), the use of merge, the time complexity is.

Guess you like

Origin www.cnblogs.com/Kaithy-Rookie/p/11329123.html