Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
一、比较排序
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
//It is a good habit that we do not revise the parameters passed from outside.
ListNode p1 = l1;
ListNode p2 = l2;
ListNode fakeHead = new ListNode(0);
ListNode cursor = fakeHead;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
cursor.next = p1;
p1 = p1.next;
} else {
cursor.next = p2;
p2 = p2.next;
}
cursor = cursor.next;
}
if (p1 != null) {
cursor.next = p1;
} else if (p2 != null) {
cursor.next = p2;
}
return fakeHead.next;
}
}
二、递归求解
public class Solution {
public 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;
}
}
}