LeetCode: Merge Two Sorted Lists
2016-08-31 00:08
330 查看
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.
源代码:
/**
* 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 == NULL) return l2;
if (l2 == NULL) return l1;
struct ListNode* head = new ListNode(0);
struct ListNode* tmp = head;
while(l1 != NULL && l2 != NULL){
if (l1->val > l2->val) {
tmp->next = l2;
l2 = l2->next;
}
else {
tmp->next = l1;
l1 = l1->next;
}
tmp = tmp->next;
}
if (l1 != NULL) tmp->next = l1;
if (l2 != NULL) tmp->next = l2;
return head->next;
}
};
源代码:
/**
* 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 == NULL) return l2;
if (l2 == NULL) return l1;
struct ListNode* head = new ListNode(0);
struct ListNode* tmp = head;
while(l1 != NULL && l2 != NULL){
if (l1->val > l2->val) {
tmp->next = l2;
l2 = l2->next;
}
else {
tmp->next = l1;
l1 = l1->next;
}
tmp = tmp->next;
}
if (l1 != NULL) tmp->next = l1;
if (l2 != NULL) tmp->next = l2;
return head->next;
}
};
相关文章推荐
- C#实现导出List数据到xml文件的方法【附demo源码下载】
- C#中list用法实例
- C#中Ilist与list的区别小结
- C#中IList<T>与List<T>的区别深入解析
- C#对list列表进行随机排序的方法
- Vc++ 控件List Control用法总结
- C++实现的泛型List类分享
- C#使用IComparer自定义List类实现排序的方法
- C# Datagridview绑定List方法代码
- C#实现DataTable,List和Json转换的方法
- javascript radio list的实现细节(多浏览器兼容)
- c++ STL容器总结之:vertor与list的应用
- Java中对List集合的常用操作详解
- java实现List中对象排序的方法
- 大家注意vector, list, set, map成员函数erase
- ASP.NET―001:GridView绑定List、页面返回值具体实现
- List all the Databases on a SQL Server
- js Map List 遍历使用示例
- Java比较两个List的值是否相等的方法
- Java List双击事件实现方法