Leetcode21.合并两个有序链表
思路:
1.比大小,小的附加在新的链表后面
2.考虑l1和l2长度不等的情况
代码
package test;
class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val=val;
}
}
public class MergeTwoLists{
public static void main(String[] args) {
ListNode l1=new ListNode(1);
l1.next=new ListNode(2);
l1.next.next=new ListNode(3);
ListNode l2=new ListNode(1);
l2.next=new ListNode(2);
l2.next.next=new ListNode(4);
ListNode result=MergeTwoListNode(l1, l2);
while(result!=null){
System.out.println(result.val);
result=result.next;
}
}
public static ListNode MergeTwoListNode(ListNode l1,ListNode l2){
ListNode result=new ListNode(0);
ListNode cur=result;
while(l1!=null && l2!=null){
if(l1.val>l2.val){
result.next=l2;
l2=l2.next;
}else{
result.next=l1;
l1=l1.next;
}
result=result.next;
}
while(l1!=null){
result.next=l1;
l1=l1.next;
result=result.next;
}
while(l2!=null){
result.next=l2;
l2=l2.next;
result=result.next;
}
return cur.next;
}
}
代码简化
while(l1!=null){
res.next=l1;
l1=l1.next;
res=res.next;
}
while(l2!=null){
res.next=l2;
l2=l2.next;
res=res.next;
}
//简化为
res.next=l1==null?l2:l1;//菜鸡想不到