输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路:
拿到这个题之后我们可以想到两种方法去解决:递归和不用递归。
不用递归的相对比较好想,就是逐个比较直到其中一个链表的节点为空,然后把剩下来的那个链表的后半部分接到目标链表最后面就可以了。
public class Solution {
public ListNode Merge(ListNode list1, ListNode list2) {
ListNode result = null;
ListNode current = null;
if (list1 == null && list2 == null) {
return null;
}
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
if (result == null) {
result = current = list1;
} else {
current.next = list1;
current = current.next;
}
list1 = list1.next;
} else {
if (result == null) {
result = current = list2;
} else {
current.next = list2;
current = current.next;
}
list2 = list2.next;
}
}
if (list1 == null) {
current.next = list2;
} else {
current.next = list1;
}
return result;
}
}
递归的方法:我们可以发现当我们取出一个节点以后不论是list1还是list2剩下的节点仍然是排好序的,所有我们可以利用这点来做递归操作。
代码:
public class Solution {
public ListNode Merge(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode result = null;
if (list1.val <= list2.val) {
result = list1;
result.next = Merge(list1.next, list2);
} else {
result = list2;
result.next = Merge(list1, list2.next);
}
return result;
}
}