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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

题解:

  简单的链表遍历,还可用递归做。

Solution 1

 v/**
* 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) {
ListNode dummy(-);
ListNode* cur = &dummy; while(l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
} cur->next = l1 ? l1 : l2; return dummy.next;
}
};

  递归方法

Solution 2

 /**
* 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) return l2;
if (!l2) return l1; if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};

最新文章

  1. 《HiWind企业快速开发框架实战》(2)使用HiWind创建自己的项目
  2. IOS照片框架
  3. wireshark基本用法及过虑规则
  4. java面试问道的
  5. 20150608_Andriod 发布问题处理
  6. 利用python建表
  7. Lucene站内搜索的设计思路
  8. WCF系统内置绑定列表与系统绑定所支持的功能
  9. Strategy 设计模式 策略模式 超靠谱原代码讲解
  10. [20190226]测试使用bbed恢复索引.txt
  11. 转://Linux Multipath多路径配置与使用案例
  12. Linux常用命令(三)查看当前计算机各方面信息
  13. Orchard Core学习一
  14. BZOJ1163&amp;BZOJ1339[Baltic2008]Mafia——最小割
  15. Codeforces 841D Leha and another game about graph - 差分
  16. C# 日文网址转punnycode
  17. MySQL中有关char、varchar、int、tinyint、decimal
  18. 63.UniquePaths II---dp
  19. 关于反序列化时抛出java.io.EOFException异常
  20. C程序设计语言(K&amp;R) 笔记1

热门文章

  1. iOS main函数讲解
  2. linux 中 用户管理 (composer 时不能root 遇到)
  3. python 统计单词出现次数
  4. 中国移动OnetNet云平台 GET指令使用
  5. eclipse新建Maven项目
  6. RabbitMQ事务确认机制(生产者)
  7. dedecms 织梦点击图片进入下一页代码
  8. 算法(Algorithms)第4版 练习 1.3.42
  9. pyqt5开发之俄罗斯方块
  10. Luogu P1196 [NOI2002]银河英雄传说:带权并查集