题目
思路
-
对于大多数情况而言
先找到两个链表里面较小的值当做起点cur
然后list1的下一个需要比较的节点作为next1,list2的下一个需要比较的节点作为next2
比较next1和next2
cur.next指向较小的那个链表节点
更新cur和next不断循环直到有一个next是null 就直接把cur.next指向不为空的那个next
-
特殊情况
对于list1,list2有一个为空的情况,返回拎一个list就行
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1==null && list2==null)return null;
if(list1==null) return list2;
if(list2==null) return list1;
ListNode ans;
ListNode cur;
ListNode next1;
ListNode next2;
if(list1.val<list2.val){
cur=list1;
ans=cur;
next1=cur.next;
next2=list2;
}
else{
cur=list2;
ans=cur;
next1=list1;
next2=cur.next;
}
while(next1!=null && next2!=null){
if(next1.val<=next2.val){
cur.next=next1;
cur=next1;
next1=cur.next;
}else{
cur.next=next2;
cur=next2;
next2=cur.next;
}
}
if (next1==null){
cur.next=next2;
}else{
cur.next=next1;
}
return ans;
}
}