Merge Two Sorted Lists(C++)
2015-10-18 10:45
429 查看
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.
Analysis
The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.
C++ Solution
Another solution , we use iteration
Analysis
The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.
C++ Solution
<span style="font-size:14px;">ListNode mergeTwoLists(ListNode L1, ListNode L2){ ListNode p1 = L1; ListNode P2 = L2; ListNode fakeHead = new ListNode(0); ListNode p = fakeHead; while(p1 != null && p2 != null){ if(p1.val <= P2.val){ p.next = p1; p1 = p1.next; }else{ p.next = p2; p2 = p2.next; } p = p.next; } if(p1 != null) p.next = p1; if(p2 != null) p.next = p2; return fakeHead.next; }</span>
Another solution , we use iteration
ListNode mergeTwoLists(ListNode L1, ListNode L2){ if(L1 == NULL) return L2; if(L2= NULL) return L1; ListNode p1 = L1; ListNode p2 = L2; ListNode fakeHead = new ListNode(0); ListNode p = fakeHead; if(p1.val < = p2.val){ p.next = mergeTwoLists(p1.next, p2); }else{ p.next = mergeTwoLists(p1, p2.next); } p = p.next; if(p1 != null) p.next = p1; if(p2 != null) p.next = p2; return fakeHead.next; }
相关文章推荐
- C语言获取文件大小相关操作
- [黑马训练营]IOS C语言分支语句
- c字符串的处理
- C++堆和栈的比较
- [黑马训练营]IOS C语言运算符
- C语言名题精选百则:所有子集,字典子集,Gray子集
- zerglurker的c语言教程006——第一功能
- 实现一个函数,判断一个数是不是素数。
- 创建一个数组, 实现初始化数组、清空数组、完成数组元素的逆置。
- 实现一个函数判断year是不是闰年。
- 实现一个函数,打印乘法口诀表,口诀表的行数和列数自己指定,输入多少打印几乘几的乘法表
- C语言基础知识
- C++ Primer章课后编程问题
- [c++]LeetCode Median of Two Sorted Arrays问题
- 剑指offer第十八题【二叉树的镜像】c++实现
- Item 41:隐式接口与编译期多态 Effective C++笔记
- 关于C语言中Implicit declaration of function ‘XXXX’ is invalid in C99警告
- <<C++标准程序库>>中的STL简单学习笔记
- C++代码静态分析工具splint
- 基础c注意点(一)