当前位置:网站首页>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;
}
};
边栏推荐
- 双指针仪表盘读数(二) ——表盘位置识别
- Quel est le risque de divulgation d'un certificat de signature de code?
- MySQL skip scan range small function to solve big problems?
- Tiktok practice ~ personal Center
- 6-32 construction of linked list by header insertion method
- 6-42 sparse matrix transpose
- 6-45 calculating the number of leaves of a binary tree
- Pytoch realizes wave impedance inversion
- PowerDesigner tip 2 trigger template
- 使用的软件是php mysql 数据库
猜你喜欢

扎克伯格最新VR原型机来了,要让人混淆虚拟与现实的那种

AttributeError: module ‘skimage.draw‘ has no attribute ‘circle‘

It was exposed that more than 170million pieces of private data had been leaked, and Xuetong responded that no clear evidence had been found

10-2xxe漏洞原理和案例实验演示

Ctfshow Web Learning Records

钟珊珊:被爆锤后的工程师会起飞|OneFlow U

Attack and defense world web practice area beginner level

字节二面:Redis主节点的Key已过期,但从节点依然读到过期数据是为什么?怎么解决?

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

Catch up with this big guy
随机推荐
Ctfshow web realizes killing through one question
谁说postgresql 没有靠谱的高可用(2)
搭建OpenPGP Key server
钟珊珊:被爆锤后的工程师会起飞|OneFlow U
2022-06-09 工作记录--yarn/npm-Error-EPERM: operation not permitted, uv_cwd
[机缘参悟-28]:鬼谷子-内揵篇-保全自己,说服上司
代碼簽名證書一旦泄露 危害有多大
缓存穿透利器之「布隆过滤器」
Cobalt strike from starting to Imprisonment (3)
6-42 sparse matrix transpose
Cobalt strike from entry to imprisonment (III)
Quickly master asp Net authentication framework identity - login and logout
[popular science] to understand supervised learning, unsupervised learning and reinforcement learning
ipv4到ipv6过渡的三种方案
力扣 1108. IP 地址无效化
Vs2022 connecting to SQLSERVER database tutorial
Aliyun OS上证书签发过程(certbot)
TCP建立连接过程(深入源码理解3次握手)
Zuckerberg's latest VR prototype is coming. It is necessary to confuse virtual reality with reality
【无标题】#修复日志#