[leetcode] 21. Merge Two Sorted Lists
来源:互联网 发布:c语言ascii码 编辑:程序博客网 时间:2024/05/20 05:47
Question:
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.
Solution:
直接模拟归并排序的合并部分,不过对象是链表指针,但是过程是一样的。
时间复杂度:O(n)
空间复杂度:O(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 && !l2) return l1; if (!l1) return l2; if (!l2) return l1; ListNode *ret; if ((l1->val < l2->val)) { ret = l1; l1 = l1->next; } else { ret = l2; l2 = l2->next; } ListNode *tmp = ret; while (l1 && l2) { if (l1->val < l2->val) { tmp->next = l1; l1 = l1->next; } else { tmp->next = l2; l2 = l2->next; } tmp = tmp->next; } while (l1) { tmp->next = l1; l1 = l1->next; tmp = tmp->next; } while (l2) { tmp->next = l2; l2 = l2->next; tmp = tmp->next; } return ret; }};
阅读全文
0 0
- 21. Merge Two Sorted Lists leetcode(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 OJ> 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists LeetCode
- leetcode 21. Merge Two Sorted Lists
- Leetcode:21. Merge Two Sorted Lists(JAVA)
- Leetcode ☞ 21. Merge Two Sorted Lists
- LeetCode 21. Merge Two Sorted Lists
- [LeetCode]21. Merge Two Sorted Lists
- 【LeetCode】21. Merge Two Sorted Lists
- 轮播图
- Socket网络通信安全
- 【面试题】锁
- C# 字符串字母的大小写组合
- lineNumber: 5; columnNumber: 451; cvc-elt.1: 找不到元素 'beans' 的声明。
- [leetcode] 21. Merge Two Sorted Lists
- Spring Data Jpa 异常:PropertyReferenceException: No property xx for type yy
- 测试连接失败,因为初始化提供程序时发生错误
- AngularJS的请求本地的json串并显示在表单上
- 实验四:用可重用的链表模块来实现命令行菜单小程序V2.5
- AngularJS Scope 表格
- Python基础详解
- OpenCV3_C++_Perspective()透视形式投影 实例
- codevs 1154 能量项链