当前位置:网站首页>Sort linked list (merge sort)
Sort linked list (merge sort)
2022-07-01 03:36:00 【Enthusiastic citizen Mr. Xue】
This question requires that O(n log n) Under time complexity and constant space complexity . In the sorting algorithm , Only quick platoon 、 The time complexity of heap and merge sort can meet the requirements , But the time complexity of fast scheduling is unstable and the space complexity is not constant , Heap is not suitable for linked list , So think about merging and sorting
public ListNode sortList(ListNode head) {
return mergeSort(head,null);
}
// Recursively separate stages
public ListNode mergeSort(ListNode head,ListNode tail){
if(head == null) return head;
When there are only two nodes left , Directly disconnect , Otherwise, it will be recursive forever
if(head.next == tail){
head.next = null;
return head;
}
Speed pointer , When the fast pointer reaches the tail node , The slow pointer will go to the middle node .
ListNode fast = head;
ListNode slow = head;
while(fast != tail){
slow = slow.next;
fast = fast.next;
if(fast != tail) fast = fast.next;
}
Record intermediate nodes , Then a recursive
ListNode mid = slow;
Recursion from head node to intermediate node
ListNode sort1 = mergeSort(head,mid);
Recursion from intermediate node to tail node
Note that you cannot start from the next in the middle like merge sorting
ListNode sort2 = mergeSort(mid,tail);
Merge section stage
ListNode res = merge(sort1,sort2);
return res;
}
// Consolidation phase
public ListNode merge(ListNode headA,ListNode headB){
Create a chain header node
ListNode dummy = new ListNode();
Temporary node , Record the end position of the linked list
ListNode temp = dummy;
ListNode tempA = headA;
ListNode tempB = headB;
while(tempA != null && tempB != null){
Put the smaller node value in front
if(tempA.val < tempB.val){
temp.next = tempA;
tempA = tempA.next;
}else{
temp.next = tempB;
tempB = tempB.next;
}
Linked list pointer backward
temp = temp.next;
}
When A Not empty , explain B It's over , Put... Directly A The rest is added to the end of the linked list
if(tempA != null) temp.next = tempA;
When B The same is true when it is not empty
if(tempB != null) temp.next = tempB;
Return to the new linked list
return dummy.next;
}
Spatial complexity log n
边栏推荐
- C#实现基于广度优先BFS求解无权图最短路径----完整程序展示
- 打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
- 数组的includes( )
- 家居网购项目
- Thread data sharing and security -threadlocal
- Introduction and installation of Solr
- Subnet division (10)
- Filter
- ES6解构语法详解
- [nine day training] content III of the problem solution of leetcode question brushing Report
猜你喜欢

Are you still wasting brain cells for self-study? This interview note is definitely the ceiling of station C

衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)

RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
![[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理](/img/9f/187ca83be1b88630a6c6fbfb0620ed.png)
[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理

Learning notes for introduction to C language multithreaded programming

Asgnet paper and code interpretation 2

Edlines: a real time line segment detector with a false detection control

JUC学习

Nacos

LeetCode 128最长连续序列(哈希set)
随机推荐
Test function in pychram
Ouc2021 autumn - Software Engineering - end of term (recall version)
Develop industrial Internet with the technical advantages of small programs
IPv4 and IPv6, LAN and WAN, gateway, public IP and private IP, IP address, subnet mask, network segment, network number, host number, network address, host address, and IP segment / number - what does
The value of the second servo encoder is linked to the NC virtual axis of Beifu PLC for display
split(),splice(),slice()傻傻分不清楚?
在线公网安备案保姆级教程【伸手党福利】
leetcode 1818 绝对值,排序,二分法,最大值
Edlines: a real time line segment detector with a false detection control
ECMAScript 6.0
Thread data sharing and security -threadlocal
【伸手党福利】JSONObject转String保留空字段
Kmeans
Pyramid Scene Parsing Network【PSPNet】论文阅读
数据库中COMMENT关键字的使用
Nacos
后台系统页面左边菜单按钮和右边内容的处理,后台系统页面出现双滚动
后台系统右边内容如何出现滚动条和解决双滚动条的问题
md5sum操作
报错:Plug-ins declaring extensions or extension points must set the singleton directive to true