java 合并2个升序单链表
时间: 2024-04-11 13:33:38 浏览: 59
以下是一个示例代码,用于合并两个升序单链表:
```java
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class MergeTwoSortedLists {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode dummy = 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);
MergeTwoSortedLists merger = new MergeTwoSortedLists();
ListNode mergedList = merger.mergeTwoLists(l1, l2);
System.out.println("合并后的链表:");
while (mergedList != null) {
System.out.print(mergedList.val + " ");
mergedList = mergedList.next;
}
}
}
```
以上代码中,我们定义了一个 `ListNode` 类表示链表的节点。`MergeTwoSortedLists` 类中的 `mergeTwoLists` 方法接收两个升序链表 `l1` 和 `l2`,并返回合并后的升序链表。在 `main` 方法中,我们创建了两个示例链表 `l1` 和 `l2`,并将它们传递给 `mergeTwoLists` 方法进行合并。最后,我们打印出合并后的链表。
希望对您有帮助!
阅读全文