2018.1.8 LeetCode 21. Merge Two Sorted Lists 【链表的基本运用】
2018-01-08 15:09
567 查看
21. Merge Two Sorted Lists
Description
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->4Output: 1->1->2->3->4->4
题意: 合并两个链表
分析: 新建一个链表,然后逐个判断即可,需要注意:
1、是否有头结点
2、l1,l2为空的情况
参考函数
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode* res = NULL; if(l1->val >= l2->val) { res = l2; l2 = l2->next; } else { res = l1; l1 = l1->next; } ListNode* p = res; // point while (l1 && l2) { if(l1->val >= l2->val) { p->next = l2; l2 = l2->next; } else { p->next = l1; l1 = l1->next; } p = p->next; } if(l1) { p->next = l1; } else { p->next = l2; } return res; } };
如有错误或遗漏,请私聊下UP,thx
相关文章推荐
- leetcode 21. Merge Two Sorted Lists 两个单向链表合并 指针与解指针
- leetcode_效率题解_[python/C++]_21. Merge Two Sorted Lists(合并2个有序链表)
- [LeetCode-21] Merge Two Sorted Lists(合并两个有序链表)
- LeetCode 21. Merge Two Sorted Lists 两个有序列表合成一个
- Leetcode 23. Merge k Sorted Lists合并k个排序链表
- 21. Merge Two Sorted Lists leetcode Python 2016 new Season
- 【LeetCode-面试算法经典-Java实现】【021-Merge Two Sorted Lists(合并两个排好序的单链表)】
- LeetCode | Merge k Sorted Lists(归并k个链表)
- 21. Merge Two Sorted Lists-leetcode-java
- LeetCode_21. Merge Two Sorted Lists
- leetcode_21题——Merge Two Sorted Lists(链表)
- LeetCode 21 Merge Two Sorted Lists 把两个链表有序连接
- leetcode---merge-two-sorted-lists---链表
- LeetCode 21 Merge Two Sorted Lists(合并链表)
- 【LeetCode-面试算法经典-Java实现】【023-Merge k Sorted Lists(合并k个排好的的单链表)】
- LeetCode | Merge Two Sorted Lists(合并两个链表)
- Leetcode Merge k Sorted Lists 合并k个链表
- [LeetCode] Merge Two Sorted Lists 混合插入有序链表
- leetcode---merge-k-sorted-lists---链表
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)