当前位置:网站首页>剑指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
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- Introduction to in-order traversal (non-recursive, recursive) after binary tree traversal
- MATLAB图形加标注的基本方法入门简介
- 推开机电的大门《电路》(二):功率计算与判断
- 质数相关问题-小记
- How to add a one-key shutdown option to the right-click menu in Windows 11
- 6. Unified logging
- 测试用例练习
- 二叉排序树与 set、map
- MATLAB绘图函数ezplot入门详解
- pytorch模型转libtorch和onnx格式的通用代码
猜你喜欢

MATLAB绘图函数plot详解

The SSE instructions into ARM NEON

Software Testing Basics (Back)

What should I do if Windows 10 cannot connect to the printer?Solutions for not using the printer

MATLAB绘图函数fplot详解

How to simulate 1/3 probability with coins, and arbitrary probability?

4.发布帖子,评论帖子

Redis common interview questions
![[STM32 Learning 1] Basic knowledge and concepts are clear](/img/1c/7c4fd2d835e15ca13517c6d97e9b3a.png)
[STM32 Learning 1] Basic knowledge and concepts are clear

Detailed explanation of MATLAB drawing function plot
随机推荐
[STM32 Learning 1] Basic knowledge and concepts are clear
Redis常见面试题
How to solve Win11 without local users and groups
Open the door to electricity "Circuit" (3): Talk about different resistance and conductance
一篇文章彻底理解Redis的持久化:RDB、AOF
MATLAB制作简易小动画入门详解
STM32LL库使用——SPI通信
轻量化AlphaPose
Configure clangd for vscode
Win11 computer off for a period of time without operating network how to solve
推开机电的大门《电路》(一):电压,电流,参考方向
Detailed introduction to the hierarchical method of binary tree creation
Letter combination of LeetCode2 phone number
模板系列-并查集
Codeforces Round #624 (Div. 3)
第二十五章:一文掌握while循环
Lightweight AlphaPose
How to reinstall Win7 system with U disk?How to reinstall win7 using u disk?
KiCad Common Shortcuts
word方框怎么打勾?