将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的

橙三吉。 提交于 2020-03-06 04:44:08

public ListNode mergeTwoLists(ListNode l1,ListNode l2){
if(l1null){
return l2;
}
if(l2
null){
return l1;
}
ListNode newhead=null;
ListNode newTail=null;
ListNode cur1=l1;
ListNode cur2=l2;
while(cur1!=null&&cur2!=null){
if(cur1.val<cur2.val){
if(newTailnull){
newhead=cur1;
newTail=cur1;
}else{
newTail.next=cur1;
newTail=newTail.next;
}
cur1=cur1.next;
}else{
if(newTail
null){
newhead=cur2;
newTail=cur2;
}else{
newTail.next=cur2;
newTail=newTail.next;
}
cur2=cur2.next;
}
}
if(cur1==null){
newTail.next=cur2;
}else{
newTail.next=cur1;
}
return newhead;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!