Merge Two Sorted Lists
2016-08-16 22:35
337 查看
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.
代码如下:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *dummy = new ListNode(0);
ListNode *MergedList = dummy;
while(l1 && l2){
if(l1->val < l2->val){
dummy->next = l1;
l1 = l1->next;
}else{
dummy->next = l2;
l2 = l2->next;
}
dummy = dummy->next;
}
if(l1){
dummy->next = l1;
}
if(l2){
dummy->next = l2;
}
return MergedList->next;
}
};
two lists.
代码如下:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode *dummy = new ListNode(0);
ListNode *MergedList = dummy;
while(l1 && l2){
if(l1->val < l2->val){
dummy->next = l1;
l1 = l1->next;
}else{
dummy->next = l2;
l2 = l2->next;
}
dummy = dummy->next;
}
if(l1){
dummy->next = l1;
}
if(l2){
dummy->next = l2;
}
return MergedList->next;
}
};
相关文章推荐
- 用VBScript写合并文本文件的脚本
- oracle列合并的实现方法
- 使用BAT一句话命令实现快速合并JS、CSS
- SQL 合并多行记录的方法总汇
- C#实现简单合并word文档的方法
- C#自适应合并文件的方法
- mysql实现合并同一ID对应多条数据的方法
- Node.js实现JS文件合并小工具
- GridView单元格合并
- 如何合并多个 .NET 程序集
- 使用UglifyJS合并/压缩JavaScript的方法
- 高性能WEB开发 JS、CSS的合并、压缩、缓存管理
- JavaScript数组合并的多种方法
- 多个js与css文件的合并方法详细说明
- 使用不同的方法结合/合并两个JS数组
- 合并Excel工作薄中成绩表的VBA代码,非常适合教育一线的朋友
- 用js实现table单元格高宽调整,兼容合并单元格(兼容IE6、7、8、FF)实例
- oracle实现多行合并的方法
- php分割合并两个字符串的函数实例
- PHP合并静态文件详解