Python 官方文档:入门教程 => 点击学习
目录问题思路版本一版本二答案版本一版本二问题 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例 1: 输入:l1 = [1,2,4
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例二:
<strong>输入:</strong>l1 = [], l2 = []
<strong>输出:</strong>[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
新建一个节点,将原来的链表都传到新的链表当中
public Listnode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode(-1);
ListNode = head;
while (list1 != null && list2 != null) {
boolean b = list1.val <= list2.val;
all.next = b ? list1 : list2;
if (b) list1 = list1.next;
else list2 = list2.next;
all = all.next;
}
all.next = list1 != null ? list1 : list2;
return head.next;
}
从原来的链表中选择出来一个进行整合,不适用任何新的内存
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null || list2 == null) {
return list1 == null ? list2 : list1;
}
ListNode head = list1.val <= list2.val ? list1 : list2;
if (list1.val <= list2.val)
list1 = list1.next;
else
list2 = list2.next;
ListNode tmp = head;
while (list1 != null && list2 != null) {
boolean b = list1.val <= list2.val;
tmp.next = b ? list1 : list2;
if (b) list1 = list1.next;
else list2 = list2.next;
tmp = tmp.next;
}
tmp.next = list1 != null ? list1 : list2;
return head;
}
到此这篇关于Java有序链表的合并实现方法的文章就介绍到这了,更多相关Java有序链表合并内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java有序链表的合并实现方法
本文链接: https://www.lsjlt.com/news/209280.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0