[Leetcode]_21 Merge Two Sorted Lists
来源:互联网 发布:python split最后一个 编辑:程序博客网 时间:2024/06/11 02:09
/** * Index: 21 * Title: Merge Two Sorted Lists * Author: ltree98 **/
将两个有序的数组合并成一个数组。
第三方介入
最通俗易懂的,设置一个第三方,来进行存储合并。
/** * 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* l3 = new ListNode(0); ListNode* head = l3; while(l1 && l2) { if(l1->val <= l2->val) { ListNode* temp = new ListNode(l1->val); l3->next = temp; l1 = l1->next; } else { ListNode* temp = new ListNode(l2->val); l3->next = temp; l2 = l2->next; } l3 = l3->next; } if(l1) l3->next = l1; else l3->next = l2; return head->next; }};
递归
/** * 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 == NULL) return l2; if(l2 == NULL) return l1; if(l1->val <= l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l1, l2->next); return l2; } }};
0 0
- [Leetcode]_21 Merge Two Sorted Lists
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- 【LeetCode】Merge Two Sorted Lists
- java中讲讲FileInputStream的用法,举例?
- JavaScript中常用的DOM操作函数
- 【leetcode】binary-tree-postorder-traversal
- mutableCopy与copy在面试中的那些坑你知道吗?
- Bootstrap初学
- [Leetcode]_21 Merge Two Sorted Lists
- ubuntu 下配置dlib-18.16 在QT中使用
- Ubuntu下用C语言访问MySQL数据库
- 【smoj 1167】松果
- java中讲讲InputStream的用法,举例?
- 程序员的底色(IDE color scheme、CLI 命令行界面)
- JAVA源码解析-LinkedList源码
- 每日三题-Day5-C(HDU 1078 FatMouse and Cheese 记忆化搜索)
- hdu 4770 Lights Against Dudely(暴力枚举dfs)