题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:
l1 = [1,2,4], l2 = [1,3,4]
输出:
[1,1,2,3,4,4]
代码实现:
结点类:
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
主函数:
public class Main{
public static void main(String[] args) {
//构造链表1
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(4);
//构造链表2
ListNode l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
//调用合并方法
ListNode res = mergeTwoLists(l1, l2);
//查看合并后的结点信息
ListNode now = res;
while (now != null) {
System.out.print(now.val + " ");//1 1 2 3 4 4
now = now.next;
}
}
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
//任意一跳链表为空时,直接返回另外一条链表
if (list1 == null) {
return list2;
} else if (list2 == null) {
return list1;
} else if (list1.val < list2.val) {
//当前层数的返回结果,放在list1后面
list1.next = mergeTwoLists(list1.next, list2);
return list1;
} else {
//当前层数链表2头结点元素 大于等于 链表1的头结点元素时,将子结果放在链表2后面,并返回链表2的头结点
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
}