合并两个有序链表(剑指offer-16)
2024-09-01 22:40:17
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解答
方法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;
}
}
最新文章
- php正则替换:
- hdu 5713(状态压缩DP)
- Eclipse 中隐藏的 5 个非常有用的功能
- 划分分区GPT11
- [Guava官方文档翻译] 1.Guava简介 (Introduction)
- Objective-c中@interface、@implementation、@protocal
- 用Spark学习矩阵分解推荐算法
- Spring-Data-JPA尝鲜:快速搭建CRUD+分页后台实例
- Mybatis+mysql批量插入性能分析测试
- EntityFrameworkCore中的实体状态
- Street Numbers POJ - 1320(佩尔方程式)
- Gradle依赖的统一管理,解决依赖冲突
- Redis集群主从复制(一主两从)搭建配置教程【Windows环境】
- 【转】MATLAB conv2函数的理解
- Visual Studio 2013编译Mozilla NPAPI 示例注意事项
- Windows 域用户
- oracle ORA-01722:无效数字 记录
- 每天一个linux命令21之ln: linux 下的软链和硬链
- Linux ping不通百度的解决方法
- Shiro的 rememberMe 功能使用指导(为什么rememberMe设置了没作用?)