1 Star 0 Fork 0

LovingL/leetcode

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
code21.java 1.95 KB
一键复制 编辑 原始数据 按行查看 历史
LovingL 提交于 2021-06-09 10:30 +08:00 . 合并两个有序链表(升序)
/**
* @Author:田宇寒.
* @Date:Created in 9:56 2021/6/9
* @Description:合并两个有序链表
* @ModifiedBy:
* @Version: 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
*/
public class code21 {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode mergeTwoListsWithIteration(ListNode l1, ListNode l2) {
/**
* create by: 田宇寒
* description: 迭代算法 时间复杂度O(m+n) 空间复杂度O(1)
* create time: 10:19 2021/6/9
* @Param: l1
* @Param: l2
* @return 'code21.ListNode'
*/
ListNode head, tail;
head = new ListNode(-1);
tail = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
tail.next = l1 == null? l2 : l1;
return head.next;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
/**
* create by: 田宇寒
* description: 递归算法 时间复杂度O(m+n) 空间复杂度O(m+n)
* create time: 10:24 2021/6/9
* @Param: l1
* @Param: l2
* @return code21.ListNode
*/
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val <= l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LovingL/leetcode.git
git@gitee.com:LovingL/leetcode.git
LovingL
leetcode
leetcode
master

搜索帮助