【剑指offer】面试题 25. 合并两个排序的链表
2024-10-09 03:39:55
面试题 25. 合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
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;
}
}
}
最新文章
- .NET平台开源项目速览(14)最快的对象映射组件Tiny Mapper
- Entity Framework 6 Recipes 2nd Edition(10-10)译 - >; 为TPH继承的插入、更新、删除操作映射到存储过程
- 解决安装rpm包依赖关系的烦恼 - yum工具介绍及本地源配置方法
- ChartDirector应用笔记(三)
- ios中摄像头/相册获取图片,压缩图片,上传服务器方法总结
- mplayer-for-windows change color scheme in win 7
- Netfilter&;iptables:如何理解连接跟踪机制?
- Android 学习历程摘要(一)
- AOE 网络
- MySQL的 explain 解析
- springmvc02
- 自学Java HashMap源码
- 非常棒的教程记录(JVM)
- Macaca自动化工具之uirecorder脚本录制
- PyPI可以使用的几个国内源
- linux下安装jdk 详细步骤(一条命令即可安装)
- vmware错误汇总
- FileReader 获取图片base64数据流 并 生成图片
- Javascript 变态题解析
- [LeetCode] 42. Trapping Rain Water_hard tag: Two Pointers
热门文章
- [php][thinkphp] 记一次Composer Linux版安装以及用它进行thinkphp项目初始化
- 中山纪中集训Day5叒是测试(划淼)
- ubuntu之路——day8.4 Adam自适应矩估计算法
- 【转】Python 深入浅出 - PyPDF2 处理 PDF 文件
- 树莓派 pip 手动安装 和使用阿里云源
- python oracle 写文件 多个SQL变量问题
- Javascript事件派发-dispatchEvent
- Typescript中的可索引接口 类类型接口
- python脚本使用源码安装不同版本的python
- Hadoop记录-HDFS均衡脚本