Leetcode 21. Merge Two Sorted Lists
2018-01-30 09:58
477 查看
原题:
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:
解决方法:
当两个列表都不为空时,每次只将小的添加到新的列表末尾。然后如果某一个列表还剩下一些数据,直接将这些数据加到新的列表末尾即可。
代码:
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
解决方法:
当两个列表都不为空时,每次只将小的添加到新的列表末尾。然后如果某一个列表还剩下一些数据,直接将这些数据加到新的列表末尾即可。
代码:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode dummy(INT_MIN); ListNode* cur = &dummy; while(l1 && 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 ? l1 : l2; return dummy.next; }
相关文章推荐
- leetcode 24. Swap Nodes in Pairs \ 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 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】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-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