当前位置:网站首页>剑指offer:合并两个排序的链表
剑指offer:合并两个排序的链表
2022-08-02 14:11:00 【超级码力奥】
我是真的傻逼。
https://www.acwing.com/solution/content/744/
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
// 我在刚开始也想到弄一个虚的头节点来着!
ListNode* dummy = new ListNode(0);
ListNode* p = dummy;
ListNode* i = l1;
ListNode* j = l2;
while(i!=NULL && j!=NULL)
{
if(i->val <= j->val)
{
p->next = i;
i = i->next;
p = p->next;
}
else
{
p->next = j;
j = j->next;
p = p->next;
}
}
p -> next = (i != NULL ? i : j);
return dummy -> next;
}
};
看看y总的多简洁:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(0);
ListNode *cur = dummy;
while (l1 != NULL && l2 != NULL) {
if (l1 -> val < l2 -> val) {
cur -> next = l1;
l1 = l1 -> next;
}
else {
cur -> next = l2;
l2 = l2 -> next;
}
cur = cur -> next;
}
cur -> next = (l1 != NULL ? l1 : l2);
return dummy -> next;
}
};
作者:yxc
链接:https://www.acwing.com/solution/content/744/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- What should I do if I install a solid-state drive in Win10 and still have obvious lags?
- 二叉排序树与 set、map
- MATLAB drawing command fimplicit detailed introduction to drawing implicit function graphics
- Redis常见面试题
- flink+sklearn——使用jpmml实现flink上的机器学习模型部署
- KiCad Common Shortcuts
- 动态规划理论篇
- 利用plot_surface命令绘制复杂曲面入门详解
- LeetCode 2353. 设计食物评分系统 维护哈希表+set
- A clean start Windows 7?How to load only the basic service start Windows 7 system
猜你喜欢
为vscode配置clangd
MATLAB绘制平面填充图入门详解
3.用户上传头像
Introduction to MATLAB drawing functions ezplot explanation
6. Unified logging
1.开发社区首页,注册
cmake configure libtorch error Failed to compute shorthash for libnvrtc.so
Win11电脑一段时间不操作就断网怎么解决
利用plot_surface命令绘制复杂曲面入门详解
Detailed explanation of MATLAB drawing function plot
随机推荐
MATLAB绘图函数fplot详解
win10怎么设置不睡眠熄屏?win10设置永不睡眠的方法
LeetCode 2353. 设计食物评分系统 维护哈希表+set
mysql学习总结 & 索引
动态数组-vector
第二十六章:二维数组
Fast advanced TypeScript
2.登录退出,登录状态检查,验证码
质数相关问题-小记
Introduction to in-order traversal (non-recursive, recursive) after binary tree traversal
1. Development community homepage, register
Software Testing Basics (Back)
总结计算机网络超全面试题
Based on the least squares linear regression equation coefficient estimation
Mapreduce环境详细搭建和案例实现
Open the door of power and electricity "Circuit" (2): Power Calculation and Judgment
Summarize computer network super comprehensive test questions
cmake配置libtorch报错Failed to compute shorthash for libnvrtc.so
Detailed explanation of MATLAB drawing function fplot
使用libcurl将Opencv Mat的图像上传到文件服务器,基于post请求和ftp协议两种方法