用链表实现合并两个升序排序的整型数组(链表)为一个新的升序整型链表并输出 Java
时间: 2024-06-16 07:08:14 浏览: 116
在Java中,可以通过链表来实现合并两个升序排序的整型数组为一个新的升序整型链表。下面是一个示例代码:
```java
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class MergeSortedLinkedList {
public static ListNode merge(ListNode l1, ListNode l2) {
ListNode = new ListNode(0);
ListNode curr = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
curr.next = l1;
l1 = l1.next;
} else {
curr.next = l2;
l2 = l2.next;
}
curr = curr.next;
}
if (l1 != null) {
curr.next = l1;
}
if (l2 != null) {
curr.next = l2;
}
return dummy.next;
}
public static void main(String[] args) {
// 创建两个升序链表
ListNode l1 = new ListNode(1);
l1.next = new ListNode(3);
l1.next.next = new ListNode(5);
ListNode l2 = new ListNode(2);
l2.next = new ListNode(4);
l2.next.next = new ListNode(6);
// 合并两个链表
ListNode mergedList = merge(l1, l2);
// 输出合并后的链表
while (mergedList != null) {
System.out.print(mergedList.val + " ");
mergedList = mergedList.next;
}
}
}
```
输出结果为:1 2 3 4 5 6
阅读全文