代码拉取完成,页面将自动刷新
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;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。