import Class19.ListNode;
/*
输入两个单调递增的链表,输出两个链表合成后的链表,
当然我们需要合成后的链表满足单调不减规则。
*/
public class Class20 {
static 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 newListHead = new ListNode(0);
ListNode p = newListHead;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
p.next = list1;
list1 = list1.next;
}else{
p.next = list2;
list2 = list2.next;
}
p = p.next;
}
if(list1 == null){
p.next = list2;
}
if(list2 == null){
p.next = list1;
}
return p.next;
}
//递归
public ListNode merge2(ListNode list1, ListNode list2){
if(list1 == null){
return list2;
}
if(list2 == null){
return list1;
}
while(list1 != null && list2 != null){
if(list1.val < list2.val){
list1.next = merge2(list1.next,list2);
return list1;
}else{
list2.next = merge2(list1,list2.next);
return list2;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}