[LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
来源:互联网 发布:软件测试策略 编辑:程序博客网 时间:2024/04/29 20:34
索引:[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. 开一个节点做 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;elsecur->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
1 0
- [LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
- [Leetcode 21, Easy] Merge Two Sorted Lists
- 【Leetcode-Easy-21】Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists (Easy)
- 21. Merge Two Sorted Lists [easy] (Python)
- LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)
- Merge Two Sorted Lists (EASY)
- 【LeetCode with Python】 Merge Two Sorted Lists
- [leetcode:python]21.Merge Two Sorted Lists
- Leetcode-Merge Two Sorted Lists-Python
- 【Leetcode】【python】Merge Two Sorted Lists
- 【LeetCode 21】Merge Two Sorted Lists(Python)
- [C++]LeetCode: 13 Merge Two Sorted Lists
- 【leetcode c++】21 Merge Two Sorted Lists
- 【LeetCode-21】 Merge Two Sorted Lists(C++)
- Leetcode 21. Merge Two Sorted Lists(C++)
- 【C++】【LeetCode】21. Merge Two Sorted Lists
- Leetcode c语言- Merge Two Sorted Lists
- C++之友元函数和友元类
- R中的apply、lapply和sapply
- [数据结构] 图的Kruskal算法实现
- MPlayer移植到EPC9600笔记
- 【OpenCV】 split和merge操作
- [LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
- HttpClient模块的HttpGet和HttpPost及Connection to refuse解决
- 用python脚本替换某文件夹下配置文件的$HOME
- C++ 类的析构函数学习笔记7
- Spring Resources接口
- 使用svn与eclipse管理本地代码
- Adding iAd in your App from Unity3d
- Android 开发 shareSDK 分享的时候 如何设置 登录和分享走客户端?
- SGU101 Domino