/**
* 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
* <p>
*
* <p>
* 示例 1:
* <p>
* <p>
* 输入:l1 = [1,2,4], l2 = [1,3,4]
* 输出:[1,1,2,3,4,4]
* 示例 2:
* <p>
* 输入:l1 = [], l2 = []
* 输出:[]
* 示例 3:
* <p>
* 输入:l1 = [], l2 = [0]
* 输出:[0]
**/
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
public static void main(String[] args) {
ListNode Node = new ListNode(1);
Node.next = new ListNode(2);
Node.next.next = new ListNode(4);
ListNode Node2 = new ListNode(1);
Node2.next = new ListNode(3);
Node2.next.next = new ListNode(4);
ListNode listNode = new Solution().mergeTwoLists(Node, Node2);
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
21. 合并两个有序链表
最新推荐文章于 2025-06-13 14:09:45 发布