输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则;
分析
先判断输入的链表是否为空的指针。如果第一个链表为空,则直接返回第二个链表;如果第二个链表为空,则直接返回第一个链表。如果两个链表都是空链表,合并的结果是得到一个空链表。
两个链表都是排序好的,我们只需要从头遍历链表,判断当前指针,哪个链表中的值小,即赋给合并链表指针即可
代码
递归版本
public class Solution {
//1->3
//2
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
if (list1.val <= list2.val) {
list1.next = Merge(list1.next, list2);
return list1;
} else {
list2.next = Merge(list1, list2.next);
return list2;
}
}
}
非递归版本
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list1;
}
if (list2 == null) {
return list2;
}
ListNode res = new ListNode(-1);
ListNode tempNode = res;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
tempNode.next = list1;
list1 = list1.next;
} else {
tempNode.next = list2;
list2 = list2.next;
}
tempNode = tempNode.next;
}
while (list1 != null) {
tempNode.next = list1;
list1 = list1.next;
tempNode = tempNode.next;
}
while (list2 != null) {
tempNode.next = list2;
list2 = list2.next;
tempNode = tempNode.next;
}
return res.next;
}