算法分析与设计课程——LeetCode刷题之Merge Two Sorted Lists
2018-01-03 00:57
537 查看
题目:
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:
答案:
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy(INT_MIN);
ListNode *tail = &dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
};
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->4 Output: 1->1->2->3->4->4
答案:
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
ListNode dummy(INT_MIN);
ListNode *tail = &dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
};
相关文章推荐
- 算法分析与设计课程——LeetCode刷题之 Merge k Sorted Lists
- 第六周算法分析与设计Ⅱ:Merge Two Sorted Lists
- (算法分析Week3)Merge Two Sorted Lists[Easy]
- 算法分析与设计课程(15):【leetcode】 Find Minimum in Rotated Sorted Array
- LeetCode :: Merge Two Sorted Lists 详细分析
- leetcode:Merge Two Sorted Lists (链接两个有序链表)【面试算法题】
- 算法分析与设计——LeetCode Problem.617 Merge Two Binary Trees
- 15算法课程 21. Merge Two Sorted Lists
- 算法分析与设计丨第三周丨LeetCode(5)——Median of Two Sorted Arrays(Hard)
- 算法分析与设计——LeetCode Problem.23 Merge k Sorted Lists
- 算法分析与设计课程——LeetCode刷题之Remove Duplicates from Sorted Array
- 【LeetCode-面试算法经典-Java实现】【021-Merge Two Sorted Lists(合并两个排好序的单链表)】
- LeetCode || Merge Two Sorted Lists
- 《leetCode》:Merge Two Sorted Lists
- leetcode-21 Merge Two Sorted Lists
- [leetcode 21] Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists
- Leetcode 21. Merge Two Sorted Lists
- leetcode-21-Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists 混合插入有序链表