当前位置:网站首页>剑指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
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
猜你喜欢

mysql学习总结 & 索引

MATLAB绘图函数fplot详解

GMP scheduling model of golang

Software Testing Basics (Back)

Installation and configuration of Spark and related ecological components - quick recall

Happy, 9/28 scene collection

Redis常见面试题

Win11 computer off for a period of time without operating network how to solve

第二十五章:一文掌握while循环

第二十六章:二维数组
随机推荐
Win10电脑需要安装杀毒软件吗?
Win10上帝模式干嘛的?Win10怎么开启上帝模式?
【系统设计与实现】基于flink的分心驾驶预测与数据分析系统
What are IPV4 and IPV6?
Exotic curiosity-a solution looking - bit operations
MATLAB绘图命令fimplicit绘制隐函数图形入门详解
Introduction to in-order traversal (non-recursive, recursive) after binary tree traversal
flink+sklearn——使用jpmml实现flink上的机器学习模型部署
质数相关问题-小记
mysql学习总结 & 索引
pytorch模型转libtorch和onnx格式的通用代码
Project: combing the database table
Publish module to NPM should be how to operate?Solutions to problems and mistake
轻量化AlphaPose
6.统一记录日志
关于c语言的调试技巧
二叉树创建之层次法入门详解
MATLAB制作简易小动画入门详解
jest test, component test
Redis常见面试题