question
code
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prehead = new ListNode(-1, null);
ListNode pre = prehead; //记录新构建链表的尾结点
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
pre.next = l1;
l1 = l1.next;
} else {
pre.next = l2;
// l2.next = l2; //error,枯了
l2 = l2.next;
}
pre = pre.next;
}
/*
最开始,没有写下面两句
没有处理:一个链表为空,另一个链表未处理完的情况
处理:直接添加到末尾即可
结果:[1,1,2,3,4]
预期结果:[1,1,2,3,4,4]
*/
if (l1 != null) pre.next = l1;
if (l2 != null) pre.next = l2;
return prehead.next;
}
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
}