题目
已知两个链表List1和List2各自有序,请把它们合并成一个链表仍然有序。
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
递归方法实现
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1 == null){
return list2;
}
if (list2 == null){
return list1;
}
ListNode head = null;
if (list1.val >= list2.val){
head = list2;
head.next = Merge(list1, list2.next);
}else {
head = list1;
head.next = Merge(list1.next, list2);
}
return head;
}
循环方法实现
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 = new ListNode(list2.val);
list2 = list2.next;
}else {
result = new ListNode(list1.val);
list1 = list1.next;
}
ListNode curNode = result;
while (list1 != null && list2 != null){
if (list1.val >= list2.val){
curNode.next = new ListNode(list2.val);
list2 = list2.next;
} else {
curNode.next = new ListNode(list1.val);
list1 = list1.next;
}
curNode = curNode.next;
}
if (list1 == null){
curNode.next = list2;
}
if (list2 == null){
curNode.next = list1;
}
return result;
}