当前位置:网站首页>剑指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 connection error solution
Win11 keeps popping up User Account Control how to fix it
Redis的线程模型
奇技淫巧-位运算
Open the door of electricity "Circuit" (1): voltage, current, reference direction
MATLAB绘制平面填充图入门详解
Codeforces Round #624 (Div. 3)
Publish module to NPM should be how to operate?Solutions to problems and mistake
flink+sklearn——使用jpmml实现flink上的机器学习模型部署
Article pygame drag the implementation of the method
如何用硬币模拟1/3的概率,以及任意概率?
pygame拖动条的实现方法
jest test, component test
7. Redis
Flink + sklearn - use JPMML implement flink deployment on machine learning model
Win11没有本地用户和组怎么解决
mysql学习总结 & 索引
项目:数据库表的梳理
深入理解Golang之Map
STM32LL库——USART中断接收不定长信息









