问题遇到的现象和发生背景
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode res = null;
ListNode root = res;
if(list1.val>list2.val){
root= res = list2;
res = res.next;
list2 = list2.next;
}
else {
root= res = list1;
res = res.next;
list1 = list1.next;
}
while(list1 != null && list2 != null)
{
if(list1.val>list2.val){
res.next = list2;
res = res.next;
list2 = list2.next;
}
else {
res.next = list1;
res = res.next;
list1 = list1.next;
}
}
if(list1 != null)
res.next = list1;
if(list2 != null)
res.next = list2;
return root;
}
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode res = null;
ListNode root = null;
while(list1 != null && list2 != null)
{
if(list1.val<list2.val){
if(res == null){
root = res = list1;
}
else{
res.next = list1;
res = res.next;
}
list1 = list1.next;
}
else {
if(res == null){
root = res = list2;
}
else{
res.next = list2;
res = res.next;
}
list2 = list2.next;
}
}
if(list1 != null)
res.next = list1;
if(list2 != null)
res.next = list2;
return root;
}
运行结果及报错内容
以上两种算法都是合并两个排序的链表的解决方法,为什么第一种算法会超时啊? 感觉相差无几,在idea下也运行时间也很长