# 21. 合并两个有序链表

21. 合并两个有序链表

https://leetcode-cn.com/problems/merge-two-sorted-lists/description/

```package com.test;

public class Lesson021 {
public static void main(String[] args) {

ListNode l11 = new ListNode(1);
ListNode l12 = new ListNode(2);
ListNode l13 = new ListNode(4);
l11.next = l12;
l12.next = l13;
printNode(l11);
ListNode l21 = new ListNode(1);
ListNode l22 = new ListNode(3);
ListNode l23 = new ListNode(4);
l21.next = l22;
l22.next = l23;
printNode(l21);
ListNode res = mergeTwoLists(l11, l21);
printNode(res);
}

private static void printNode(ListNode l11) {
System.out.print(l11.val);
if(l11.next != null){
System.out.print("->");
printNode(l11.next);
}else{
System.out.println("");
}
}

private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if (l2 == null) {
return l1;
}
int val1 = l1.val;
int val2 = l2.val;
if (val1 > val2) {
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}else{
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}

}
}```

21. 合并两个有序链表

(0)
(0)

0条