[Leetcode] Merge Two Sorted Lists
来源:互联网 发布:华为网络机顶盒怎么样 编辑:程序博客网 时间:2024/05/17 22:59
描述
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.
将两个有序链表合并。
分析1
这道题可以使用递归的方法来完成,当两个链表都非空时,将两个表头中值较小的一个加入答案,同时该表头向后移动一位,当两个链表有一个空时,将另外一个链表加入答案。
代码1
/** * 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; } }};
分析2
根据递归的代码可以很容易改为非递归的,代码如下。
代码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) { ListNode *dummy = new ListNode(-1), *p = dummy; while (l1 && l2) { if (l1->val <= l2->val) { p->next = l1; l1 = l1->next; p = p->next; } else { p->next = l2; l2 = l2->next; p = p->next; } } if (l1) p->next = l1; else p->next = l2; return dummy->next; }};
0 0
- 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
- Leetcode Merge Two Sorted Lists
- SpringBoot 中使用 Log4j
- 【备忘】两套 Swift视频教程 完整版 下载
- 56.贝赛尔曲线初步(一)
- Oracle执行DDL语句结束后加/,打补丁把/换成GO
- 最少拦截系统
- [Leetcode] Merge Two Sorted Lists
- 购买阿里云免费https证书,配置tomcat实现https加密访问
- SSH框架中配置log4j的方法
- 房地产不良资产的形成原因
- gts 测试 - 4.1_r1
- Android Studio中Junit调试
- sklearn学习笔记(1)--make_blobs
- 虚拟机的安装
- 查询SQL数据库中的schema