面试题 25. 合并两个排序的链表

NowCoder

题目描述

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

Java 实现

ListNode Class

class ListNode {
int val;
ListNode next = null; ListNode(int val) {
this.val = val;
} @Override
public String toString() {
return val + "->" + next;
}
}

Iterative Solution

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

Recursive Solution

public class Solution {
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.val <= list2.val) {
list1.next = Merge(list1.next, list2);
return list1;
} else {
list2.next = Merge(list1, list2.next);
return list2;
}
}
}

最新文章

  1. .NET平台开源项目速览(14)最快的对象映射组件Tiny Mapper
  2. Entity Framework 6 Recipes 2nd Edition(10-10)译 - &gt; 为TPH继承的插入、更新、删除操作映射到存储过程
  3. 解决安装rpm包依赖关系的烦恼 - yum工具介绍及本地源配置方法
  4. ChartDirector应用笔记(三)
  5. ios中摄像头/相册获取图片,压缩图片,上传服务器方法总结
  6. mplayer-for-windows change color scheme in win 7
  7. Netfilter&amp;iptables:如何理解连接跟踪机制?
  8. Android 学习历程摘要(一)
  9. AOE 网络
  10. MySQL的 explain 解析
  11. springmvc02
  12. 自学Java HashMap源码
  13. 非常棒的教程记录(JVM)
  14. Macaca自动化工具之uirecorder脚本录制
  15. PyPI可以使用的几个国内源
  16. linux下安装jdk 详细步骤(一条命令即可安装)
  17. vmware错误汇总
  18. FileReader 获取图片base64数据流 并 生成图片
  19. Javascript 变态题解析
  20. [LeetCode] 42. Trapping Rain Water_hard tag: Two Pointers

热门文章

  1. [php][thinkphp] 记一次Composer Linux版安装以及用它进行thinkphp项目初始化
  2. 中山纪中集训Day5叒是测试(划淼)
  3. ubuntu之路——day8.4 Adam自适应矩估计算法
  4. 【转】Python 深入浅出 - PyPDF2 处理 PDF 文件
  5. 树莓派 pip 手动安装 和使用阿里云源
  6. python oracle 写文件 多个SQL变量问题
  7. Javascript事件派发-dispatchEvent
  8. Typescript中的可索引接口 类类型接口
  9. python脚本使用源码安装不同版本的python
  10. Hadoop记录-HDFS均衡脚本