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

奇技淫巧-位运算

Based on the least squares linear regression equation coefficient estimation

MATLAB绘图命令fimplicit绘制隐函数图形入门详解

利用plot_surface命令绘制复杂曲面入门详解

第三十三章:图的基本概念与性质

Network Security Packet Capture

Win11 system cannot find dll file how to fix

STM32LL library - USART interrupt to receive variable length information

5.事务管理

MATLAB图形加标注的基本方法入门简介
随机推荐
Open the door of electricity "Circuit" (1): voltage, current, reference direction
Use libcurl to upload the image of Opencv Mat to the file server, based on two methods of post request and ftp protocol
第三十三章:图的基本概念与性质
轻量化AlphaPose
基于矩阵计算的线性回归分析方程中系数的估计
倍增和稀疏表
Win11 computer off for a period of time without operating network how to solve
How to add a one-key shutdown option to the right-click menu in Windows 11
用U盘怎么重装Win7系统?如何使用u盘重装系统win7?
使用libcurl将Opencv Mat的图像上传到文件服务器,基于post请求和ftp协议两种方法
1.开发社区首页,注册
IPV4和IPV6是什么?
Win11 keeps popping up User Account Control how to fix it
Lightweight AlphaPose
Codeforces Round #605 (Div. 3)
Masters and Masters
6.统一记录日志
推开机电的大门《电路》(一):电压,电流,参考方向
Redis常见面试题
动态数组-vector