一开始写的没有注意到在while中判断的时候需要判断 l1 和 l2 同时不能为空,否则会一直在循环里,且由于某一个链表走到最后以后再取值会报错,初始链表应该用new ListNode(0)来初始化
package leetcode; /** * @author doyinana * @create 2020-05-01 13:01 */ public class L21 { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head1=l1; ListNode head2=l2; ListNode head=null; ListNode cur=head; while(l1!=null||l2!=null){ if(l1.val<=l2.val){ cur.next=l1; l1=l1.next; cur=cur.next; }else{ cur.next=l2; l2=l2.next; cur=cur.next; } } while (l1!=null){ cur.next=l1; cur=cur.next; l1=l1.next; } while (l2!=null){ cur.next=l2; cur=cur.next; l2=l2.next; } return head; } }
正确的写法如下:
迭代解法
package leetcode; /** * @author doyinana * @create 2020-05-01 13:01 */ public class L21 { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode tail = dummyHead; while (l1 != null && l2 != null) { if (l1.val < l2.val) { tail.next = l1; l1 = l1.next; } else { tail.next = l2; l2 = l2.next; } tail = tail.next; } tail.next = l1 == null? l2: l1; return dummyHead.next; } }
递归解法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } if (l1.val <= l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } l2.next = mergeTwoLists(l1, l2.next); return l2; } }