LC_21_Merge Two Sorted Lists

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC_21_Merge Two Sorted Lists相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/merge-two-sorted-lists/description/
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 

 1   // time o(n): while loop sapce o(1): one stack
 2     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 3         ListNode dummy = new ListNode(0);
 4         ListNode curr =  dummy;
 5         // l1 l2 two heads w   e dont need to keep, so we use them as counter: so we dont need to check l1.next or l2.next
 6         while (l1!=null && l2 != null){
 7             if (l1.val <= l2.val){
 8                 curr.next = l1 ;
 9                 l1 = l1.next ;
10             }else{
11                 curr.next = l2;
12                 l2 = l2.next ;
13             }
14             curr = curr.next ;
15         }
16         //either side is null, check the other
17         if (l1 != null){
18             curr.next = l1 ;
19         }
20         if (l2 != null){
21             curr.next = l2 ;
22         }
23         //serve as default for if either l1 is null or l2 is null or reach the end
24         return dummy.next;
25     }
26 
27     /*
28     *   Input: 1->2->4, 1->3->4
29         Output: 1->1->2->3->4->4
30     * */
31     // time: o(n) space: o(n)-recursive on n stacks
32     public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
33         /* recursive: subproblem: l1,l2 -> l1.next or l2.next but not l1.next && l2.next
34         *               rule: l1.val <= l2    l1.next->l1.next
35         *                     l2.val< l1      l2.next->l2.next
36         *               base l1 == null return l2; l2 == null return l1
37         * */
38         if (l1 == null) return l2 ;
39         if (l2 == null) return l1 ;
40         if (l1.val <= l2.val){
41             l1.next = mergeTwoLists2(l1.next, l2);
42             return l1 ;
43         } else{
44             l2.next = mergeTwoLists2(l1, l2.next) ;
45             return l2 ;
46         }
47         //这样写的错误在于,L1 L2 只链接了一个点
48 //        ListNode newHead = mergeTwoLists2(l1.next, l2.next) ;
49 //        if (l1.val <= l2.val) {
50 //            l1.next = newHead ;
51 //            return l1 ;
52 //        } else{
53 //            l2.next = newHead ;
54 //            return l2 ;
55 //        }
56     }

 

以上是关于LC_21_Merge Two Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

21. Merge Two Sorted Lists

乘风破浪:LeetCode真题_021_Merge Two Sorted Lists

21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

21.Merge Two Sorted Lists(链表)

21. Merge Two Sorted Lists