Ai
1 Star 0 Fork 0

wu-xjg/LeetCode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Code21.java 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
wu-xjg 提交于 2025-02-18 22:18 +08:00 . day02
package Code;
import java.util.List;
public class Code21 {
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while(list1 != null && list2!= null){
if(list1.val <= list2.val){
p.next = list1;
list1 = list1.next;
}else{
p.next = list2;
list2 = list2.next;
}
p = p.next;
}
p.next = list1 == null? list2: list1;
return dummy.next;
}
public static void main(String[] args) {
// 构建示例链表 1: 1 -> 2 -> 4
ListNode list1 = new ListNode(1);
list1.next = new ListNode(2);
list1.next.next = new ListNode(4);
// 构建示例链表 2: 1 -> 3 -> 4
ListNode list2 = new ListNode(1);
list2.next = new ListNode(3);
list2.next.next = new ListNode(4);
ListNode mergedList = mergeTwoLists(list1, list2);
// 打印合并后的链表
ListNode current = mergedList;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wu-xjg/leet-code.git
git@gitee.com:wu-xjg/leet-code.git
wu-xjg
leet-code
LeetCode
master

搜索帮助