21. Merge Two Sorted Lists【easy】

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 || l2 == NULL) {
return l1 ? l1 : l2;
} ListNode * dummy = new ListNode(INT_MIN);
ListNode * temp = dummy; while (l1 && l2) {
if (l1->val > l2->val) {
dummy->next = l2;
l2 = l2->next;
}
else {
dummy->next = l1;
l1 = l1->next;
} dummy = dummy->next;
} if (l1 || l2) {
dummy->next = l1 ? l1 : l2;
} return temp->next;
}
};

由于最后是弄到list1中,但是我们不知道list1还是list2的第一个元素关系,最后结果的list1中的头结点可能会改变,所以需要引入dummy节点。

解法二:

 public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
if(l2 == null) return l1;
if(l1.val < l2.val){
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else{
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}

参考了@yangliguang 的代码

解法三:

 public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1; ListNode handler;
if(l1.val < l2.val) {
handler = l1;
handler.next = mergeTwoLists(l1.next, l2);
} else {
handler = l2;
handler.next = mergeTwoLists(l1, l2.next);
} return handler;
}
}

参考了@RunRunCode 的代码

解法二和解法三都是递归,还没有完全弄明白……

最新文章

  1. Eclipse中的Link with Editor功能是如何实现
  2. C#设计模式-单例模式
  3. RabbitMQ中 exchange、route、queue的关系
  4. shell切割日志脚本
  5. (3)VS2010+Opencv-2.4.8的配置攻略
  6. java开发规范总结_代码注释规范
  7. swing的第一课
  8. 使用Visual Studio创建映像向导(Image Sprite)——Web Essential
  9. centos下 apache+mysql+php的安装
  10. Glide的 java.lang.RuntimeException: Expected instanceof GlideModule, but found:X.GlideModule@2e4554f
  11. Linux记录-linux系统监控命令汇总
  12. git迁移
  13. wvblk 把 xp、2003、win7(32位) 装入 VHD
  14. Unity AssetBoundle 打包流程
  15. [UE4]修改枪支碰撞体
  16. python文件相关操作
  17. __str__被print函数调用,目的是打印类的内容到屏幕上
  18. java中常见异常汇总(根据自己遇到的异常不定时更新)
  19. java 读入文件 FileInputStream
  20. Apache版Phoenix的安装(图文详解)

热门文章

  1. small test on 5.30 night T1
  2. [BZOJ4538]网络
  3. [CEOI2017]One-Way Streets
  4. IO多路复用 select、poll、epoll
  5. nullptr 与 constexpr
  6. python中list/tuple/dict/set的区别
  7. convert image to base64
  8. [原创]用逻辑嗅探破解接触式IC卡口令
  9. XPath注入技术综述
  10. 配置SSH单向无密码访问