当前位置:网站首页>LeetCode Algorithm 21. 合并两个有序链表
LeetCode Algorithm 21. 合并两个有序链表
2022-06-22 10:10:00 【Alex_996】
题目链接:21. 合并两个有序链表
Ideas
算法:归并排序最后Merge
数据结构:链表
思路:这道题考察的就是归并排序最后两个有序链表合并的阶段。首先还是要创建一个空链表res用来表示最终的返回结果。然后对于两个链表的指针,开始分别指向两个链表的第一个元素,然后两个指针往前走,并比较相应位置上元素的大小,取大的那个元素拿到res,以此类推最终直到有一个指针走到相应链表的末尾。最后有可能其中一个指针没有走到链表末尾,那么直接将res的下一个元素指向该指针对应的链表即可。
补充:关于归并排序的具体实现和动画演示可以参考博客:教小学妹学算法:十大经典排序算法深度解析
Code
C++
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* res = new ListNode(-1);
ListNode* prev = res;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
prev->next = list1;
list1 = list1->next;
} else {
prev->next = list2;
list2 = list2->next;
}
prev = prev->next;
}
prev->next = list1 == nullptr ? list2 : list1;
return res->next;
}
};
边栏推荐
- Thinkphp3.2.3 log inclusion analysis
- Encryption market plummeted, Seth triggered a new round of concern
- 6-40 constructing ordered sparse polynomial chained storage
- 《网络安全等级保护基本要求》(GBT 22239-2019)标准解读
- QT compile the Internet of things management platform 36- communication protocol
- 如何将数据库中的值经过Servlet传到jsp页面通过EL表达式中显示出来?
- [structure training camp - module 3]
- 10-2xxe vulnerability principle and case experiment demonstration
- thinkphp3.2.3日志包含分析
- Quel est le risque de divulgation d'un certificat de signature de code?
猜你喜欢

HMS core news industry solution: let technology add humanistic temperature

MySQL skip scan range small function to solve big problems?

Qt编写物联网管理平台36-通信协议

传iPhone 14将全系涨价;TikTok美国用户数据转移到甲骨文,字节无法访问;SeaTunnel 2.1.2发布|极客头条...
![[untitled] repair log](/img/8c/e05098c3731b4efce270108d6c52a7.png)
[untitled] repair log

QT compile the Internet of things management platform 36- communication protocol

After using Matplotlib for so long, I didn't know that the data could move

一口气读懂 IT发展史

大学生期末考试SQL语句

IDE 的主题应该用亮色还是暗色?终极答案来了!
随机推荐
QT compile the Internet of things management platform 36- communication protocol
7-1 group minimum
Vs2022 connecting to SQLSERVER database tutorial
systemd 总结 介绍
Encryption market plummeted, Seth triggered a new round of concern
Pytorch实现波阻抗反演
Bloom filter optimization - crimsondb series of papers (I)
一口气读懂 IT发展史
What kind of experience is middle-aged unemployment
2022-06-09 work record --yarn/npm-error-eperm: operation not permitted, UV_ cwd
Cobalt strike from entry to imprisonment (III)
搭建OpenPGP Key server
thinkphp5.0.24反序列化漏洞分析
Evaluation of scientific research award and entrepreneurship Award
Should the theme of the IDE be bright or dark? Here comes the ultimate answer!
Bluetooth, WiFi, ZigBee, Lora, Nb lot, call signal, network signal 4G
【无标题】#修复日志#
ipv4到ipv6过渡的三种方案
Aliyun OS上证书签发过程(certbot)
Target detection / segmentation training using pytorch mask RCNN