输入两个递增排序的链表,合并这两个链表并使这两个链表中的节点交叉相叠。
示例1:
输入:1->3->4, 1->2->4
输出:1->1->3->2->4->4
解决思路:1>迭代法
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) {
return l2;
}
if(l2 == null) {
return l1;
}
ListNode head = l1;
ListNode temp1 = l1.next;
ListNode temp2 = l2.next;
l1.next = l2;
l1.next.next = temp1;
l1 = l1.next.next;
while(l1 != null) {
temp1 = l1.next;
l1.next = temp2;
temp2 = l1.next.next;
l1.next.next = temp1;
l1 = l1.next.next;
}
return head;
}
2>递归法:
public ListNodemergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) {
return l2;
}
if(l2==null) {
return l1;
}
l1.next = mergeTwoLists(l2, l1.next);
return l1;
}