将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
思路
(1)一次只抓住一个结点。动了之后移动指针。参见剑指Offer-链表-面试题25:合并两个排序的链表
(2)error1:忽略了长短链表的之后指针没变动,应该直接return 链表。
解法-AC
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode head2 = head;
while(l1!=null || l2 !=null){
if(l1!=null && l2!=null){
if(l1.val < l2.val){
head.next = l1;
head =head.next;
l1 = l1.next;
}else{
head.next = l2;
head = head.next;
l2 =l2.next;
}
}else if(l1 != null){
head.next =l1;
return head2.next;
}else {
head.next = l2;
return head2.next;
}
}
return head2.next;
}
}