码迷,mamicode.com
首页 > 其他好文 > 详细

LC_21_Merge Two Sorted Lists

时间:2018-02-21 23:37:28      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:ase   default   ems   and   pac   merge   pos   stack   script   

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

标签:ase   default   ems   and   pac   merge   pos   stack   script   

原文地址:https://www.cnblogs.com/davidnyc/p/8457737.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!