【LeetCode】021. Merge Two Sorted Lists
2024-08-30 02:23:51
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
题解:
简单的链表遍历,还可用递归做。
Solution 1
v/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dummy(-);
ListNode* cur = &dummy; while(l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
} cur->next = l1 ? l1 : l2; return dummy.next;
}
};
递归方法
Solution 2
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1; if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
最新文章
- 《HiWind企业快速开发框架实战》(2)使用HiWind创建自己的项目
- IOS照片框架
- wireshark基本用法及过虑规则
- java面试问道的
- 20150608_Andriod 发布问题处理
- 利用python建表
- Lucene站内搜索的设计思路
- WCF系统内置绑定列表与系统绑定所支持的功能
- Strategy 设计模式 策略模式 超靠谱原代码讲解
- [20190226]测试使用bbed恢复索引.txt
- 转://Linux Multipath多路径配置与使用案例
- Linux常用命令(三)查看当前计算机各方面信息
- Orchard Core学习一
- BZOJ1163&;BZOJ1339[Baltic2008]Mafia——最小割
- Codeforces 841D Leha and another game about graph - 差分
- C# 日文网址转punnycode
- MySQL中有关char、varchar、int、tinyint、decimal
- 63.UniquePaths II---dp
- 关于反序列化时抛出java.io.EOFException异常
- C程序设计语言(K&;R) 笔记1