题解 | #合并有序链表#
合并有序链表
http://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d
public ListNode mergeTwoLists (ListNode l1, ListNode l2) { // write code here //1.新建链表head,辅助变量cur=head,head需要返回 //2.遍历比较l1和l2的值,把小的接在cur后面,小的后移,cur后移 //3.可能l1比较长,剩下的接到cur后面 if(l1==null) return l2; if(l2==null) return l1; ListNode head=new ListNode(0); ListNode cur=head; while(l1!=null&&l2!=null){ if(l1.val<=l2.val){ cur.next=l1; l1=l1.next; }else{ cur.next=l2; l2=l2.next; } cur=cur.next; } cur.next=(l1==null)?l2:l1; return head.next; //head定义时值为0,不包含在内,取next }