LeetCode 21. Merge Two Sorted Lists

原题链接在这里:https://leetcode.com/problems/merge-two-sorted-lists/

题目:

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.

题解:

Method 1:

recursion, stop condition: 一条list 空了,返回另外一条。否则比较两个node value, 取小的,对应的点后移,next 指向用作下次比较返回的结果。

Time Complexity: O(m+n), m 是list1的长度,n 是list2 的长度.

Space: recursion 用的stack的大小, O(m+n).

Method 2:

Iteration, 生成一个dummy, 对应生成currentNode 用来iterate. 每次比较两个点,小的连在current 的后面直到 一个为 null, 再把没iterate完的那个连在current后面即可.

Time Complexity: O(m+n).

Space O(1). 

AC Java:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
14         /*
15         //Method 1, Recursion
16         if(l1 == null){
17             return l2;
18         }
19         if(l2 == null){
20             return l1;
21         }
22         
23         ListNode mergeHead;
24         if(l1.val <= l2.val){
25             mergeHead = l1;
26             mergeHead.next = mergeTwoLists(l1.next,l2);
27         }else{
28             mergeHead = l2;
29             mergeHead.next = mergeTwoLists(l1,l2.next);
30         }
31         
32         return mergeHead;
33         */
34         
35         //Method 2, Iteration
36         if(l1 == null){
37             return l2;
38         }
39         if(l2 == null){
40             return l1;
41         }
42         ListNode dummy = new ListNode(0);
43         ListNode current = dummy;
44         while(l1!=null && l2!= null){
45             if(l1.val<=l2.val){
46                 current.next = l1;
47                 l1 = l1.next;
48                 current = current.next;
49             }else{
50                 current.next = l2;
51                 l2 = l2.next;
52                 current = current.next;
53             }
54         }
55         if(l1 != null){
56             current.next = l1;
57         }
58         if(l2 != null){
59             current.next = l2;
60         }
61         return dummy.next;
62     }
63 }

跟上 Merge k Sorted ListsMerge Sorted Array.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4876421.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值