题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

解答
方法1:递归

 /*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null) return list2;//递归终止条件
if(list2 == null) return list1;//递归终止条件
if(list1 == null && list2 == null) return null;//递归终止条件
ListNode head = null;
if(list1.val>=list2.val){
head = list2;
list2.next = Merge(list1,list2.next);}
else{
head = list1;
list1.next = Merge(list1.next,list2);}
return head;
}
}

图片引用自:https://blog.csdn.net/fengpojian/article/details/81384130

方法2:迭代

 /*
public class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode head = new ListNode(-1);
ListNode cur = head;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
cur.next = list1;
list1 = list1.next;
} else {
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}
if (list1 != null)
cur.next = list1;
if (list2 != null)
cur.next = list2;
return head.next;
}
}

最新文章

  1. php正则替换:
  2. hdu 5713(状态压缩DP)
  3. Eclipse 中隐藏的 5 个非常有用的功能
  4. 划分分区GPT11
  5. [Guava官方文档翻译] 1.Guava简介 (Introduction)
  6. Objective-c中@interface、@implementation、@protocal
  7. 用Spark学习矩阵分解推荐算法
  8. Spring-Data-JPA尝鲜:快速搭建CRUD+分页后台实例
  9. Mybatis+mysql批量插入性能分析测试
  10. EntityFrameworkCore中的实体状态
  11. Street Numbers POJ - 1320(佩尔方程式)
  12. Gradle依赖的统一管理,解决依赖冲突
  13. Redis集群主从复制(一主两从)搭建配置教程【Windows环境】
  14. 【转】MATLAB conv2函数的理解
  15. Visual Studio 2013编译Mozilla NPAPI 示例注意事项
  16. Windows 域用户
  17. oracle ORA-01722:无效数字 记录
  18. 每天一个linux命令21之ln: linux 下的软链和硬链
  19. Linux ping不通百度的解决方法
  20. Shiro的 rememberMe 功能使用指导(为什么rememberMe设置了没作用?)

热门文章

  1. 为什么阿里巴巴Java开发手册中不允许魔法值出现在代码中?
  2. ubuntu12.04 qtcreate支持中文输入
  3. Jmeter环境部署
  4. Thread基础-创建线程的方式
  5. 安装并配置Samba
  6. 【JMeter_18】JMeter逻辑控制器__吞吐量控制器&lt;Throughput Controller&gt;
  7. liunx 常用快捷键
  8. Java 多线程基础(八)线程让步
  9. leetcode-cn 剑指offer
  10. sharding-jdbc源码解析