题目
题解
代码
/** * Definition for singly-linked list. public class ListNode { int val; ListNode * next; ListNode(int x) { val = x; } } */
public class code21 {
// public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// ListNode prehead = new ListNode(-1);
// ListNode prev = prehead;
// while (l1 != null && l2 != null) {
// if (l1.val <= l2.val) {
// prev.next = l1;
// l1 = l1.next;
// } else {
// prev.next = l2;
// l2 = l2.next;
// }
// prev = prev.next;
// }
// prev.next = (l1 == null ? l2 : l1);
// return prehead.next;
// }
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;
}
}
// 方法:遍历链表( 打印输出链表。方法的参数表示从节点node开始进行遍历)
public static void print(ListNode node) {
if (node == null) {
return;
}
ListNode current = node;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(4);
listNode1.next = listNode2;
listNode2.next = listNode3;
ListNode listNode4 = new ListNode(1);
ListNode listNode5 = new ListNode(3);
ListNode listNode6 = new ListNode(4);
listNode4.next = listNode5;
listNode5.next = listNode6;
ListNode result = mergeTwoLists(listNode1, listNode4);
print(result);
}
}