zoukankan      html  css  js  c++  java
  • LeetCode 21. Merge Two Sorted Lists(easy 难度)

    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

    题目要求合并了两个排序链表,首先可以用递归的方法解决,代码不复杂,但是需要确定递归的终止条件(遇见null)以及更简单递归的调用(访问某个参数的next),递归的代码如下:
     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    12         if (l1 == nullptr)
    13             return l2;
    14         if (l2 == nullptr)
    15             return l1;
    16         //用递归的方法解决问题
    17         if (l1->val < l2->val)
    18         {
    19             l1->next = mergeTwoLists(l1->next, l2);
    20             return l1;
    21         }
    22         else
    23         {
    24             l2->next = mergeTwoLists(l1, l2->next);
    25             return l2;
    26         }
    27     }
    28 };
    • 时间复杂度:O(m*n)  m和n分别表示两个链表的长度
    • 空间复杂度:O(m*n)

    当然这道题也可以用非递归的解法,时间复杂度不变,空间复杂度降为O(1),而且不会产生栈溢出的问题,代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    12        //考虑到到底归的方法空间复杂度比较大而且可能导致栈溢出,这里采用迭代的方法
    13         ListNode* preHead = new ListNode(-1);
    14         ListNode* prev = preHead;  //记录当前节点的上一个节点  l1和l2则指向下一个待分配的节点
    15         while (l1 != nullptr && l2 != nullptr)
    16         {
    17             if (l1->val <= l2->val)
    18             {
    19                 prev->next = l1;
    20                 l1 = l1->next;
    21             }
    22             else
    23             {
    24                 prev->next = l2;
    25                 l2 = l2->next;
    26             }
    27             prev = prev->next;
    28         }
    29         prev->next = (l1==nullptr) ? l2 : l1;
    30         return preHead->next;
    31         
    32         
    33     }
    34 };
  • 相关阅读:
    Git学习手记(一)
    微信开发手记(二)
    mysql命令行打开中文乱码
    在linux上centos6安装pdo_mysql扩展
    在linux上安装php5.6版本提示GD2版本要高于2.1.0解决
    在linux上安装apache是出现error1错误
    在linux上搭建amp环境安装jpeg时出现libtool command not found,error127解决
    在linux中搭建amp环境(apache2.4.7+mysql5.5.23+php5.6.19)
    mysql忘记root密码解决办法
    移动端网页设计经验与心得
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/7987176.html
Copyright © 2011-2022 走看看