table of Contents
Solution 1: Iteration (new linked list)
topic:
https://leetcode-cn.com/problems/merge-two-sorted-lists/
Combine the two ascending linked lists into a new ascending linked list and return. The new linked list is composed by splicing all the nodes of the given two linked lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution 1: Iteration (new linked list)
/**
* 思路:
* 新建一个节点
* 一直往前遍历2个链表
* 比较l1和l2的值,新链表指向值小的那个节点
* 如果一个链表走完了,直接把另一个链表加过去
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode node=head;
while (l1!=null&&l2!=null){
if (l1.val<l2.val){
node.next=l1;
node=node.next;
l1=l1.next;
}else {
node.next=l2;
node=node.next;
l2=l2.next;
}
}
node.next=l1==null?l2:l1;
return head.next;
}
Time complexity: On
Space complexity: O1
Solution 2: Recursion
/**
* 思路:
* 递归,每层找到最小的,指向下一个小的(递归的在去找小的)
* 如果走完了一个链条,直接返回另外一个链条就是最终的结果
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1==null)return l2;
if (l2==null)return l1;
if (l1.val>l2.val){
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}else {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
}
Time complexity: On
Space complexity: O1