- 题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
- 迭代法
主要要注意链表节点的赋值问题!!!
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
ListNode pre = new ListNode(0);
ListNode tail = pre;
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;
}
while (l1 != null){
tail.next = l1;
l1 = l1.next;
tail = tail.next;
}
while (l2 != null){
tail.next = l2;
l2 = l2.next;
tail = tail.next;
}
return pre.next;
}