[LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode


021.Merge_Two_Sorted_Lists (Easy)

链接

题目:https://oj.leetcode.com/problems/merge-two-sorted-lists/
代码(github):https://github.com/illuz/leetcode

题意

合并两个有序链表。

分析

很经典的题目,不过知道怎样做后很容易,摹拟便可。
有两种做法:
1. 开1个节点做 head 的前节点 (下面的 Python 代码实现)
2. 不开直接做(C++ 代码实现)

代码

C++:

class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;

ListNode *start, *cur;

if (l1->val < l2->val) {
cur = start = l1;
l1 = l1->next;
} else {
cur = start = l2;
l2 = l2->next;
}
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
cur->next = l1;
cur = l1;
l1 = l1->next;
} else {
cur->next = l2;
cur = l2;
l2 = l2->next;
}
}
if (l1 != NULL)
cur->next = l1;
else
cur->next = l2;
return start;
}
};

ListNode *l1, *l2, *ll1, *ll2;
int main() {
int n1, n2;
Solution s;
cin >> n1;
ll1 = l1 = new ListNode(0);
for (int i = 0; i < n1; i++) {
l1->next = new ListNode(0);
l1 = l1->next;
scanf("%d", &(l1->val));
}
cin >> n2;
ll2 = l2 = new ListNode(0);
for (int i = 0; i < n2; i++) {
l2->next = new ListNode(0);
l2 = l2->next;
scanf("%d", &(l2->val));
}
ListNode *res = s.mergeTwoLists(ll1->next, ll2->next);
while (res != NULL) {
cout << res->val << ' ';
res = res->next;
}

return 0;
}

Python:

class Solution:
# @param two ListNodes
# @return a ListNode
def mergeTwoLists(self, l1, l2):
if not l1 and not l2:
return None

dummy = ListNode(0)
cur = dummy
while l1 and 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 or l2

return dummy.next

波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!

波比源码 » [LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)

发表评论

Hi, 如果你对这款模板有疑问,可以跟我联系哦!

联系站长
赞助VIP 享更多特权,建议使用 QQ 登录
喜欢我嘛?喜欢就按“ctrl+D”收藏我吧!♡