合并两个链表
1.问题描述
description:
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
2.思路
将头部较小的链表的节点与另一个链表合并,递归解答。
退出条件为:当一个链表为空时,返回另一个链表剩下的元素,那么上层方法中,next即为返回值,依次返回,获得合并链表。
public class MergeTwoSortedLists {
public static void main(String[] args) {
ListNode l1 = new ListNode(1);
l1.next=new ListNode(2);
l1.next.next=new ListNode(3);
ListNode l2 = new ListNode(2);
l2.next=new ListNode(2);
l2.next.next=new ListNode(8);
ListNode node = mergeTwoLists(l1, l2);
System.out.println(node);
}
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}

浙公网安备 33010602011771号