zoukankan      html  css  js  c++  java
  • LeetCode21:合并两个有序链表

    将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4

    很简单的循环判断,但是申请了一个dummyhead的空间。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode() : val(0), next(nullptr) {}
     7  *     ListNode(int x) : val(x), next(nullptr) {}
     8  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     9  * };
    10  */
    11 class Solution {
    12 public:
    13     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    14         ListNode *combine = new ListNode;
    15         ListNode *dummyhead=combine;
    16         while(l1!=NULL && l2!=NULL){
    17             if(l1->val<l2->val){
    18                 combine->next=l1;
    19                 l1=l1->next;
    20                 combine=combine->next;
    21             }
    22             else{
    23                 combine->next=l2;
    24                 l2=l2->next;
    25                 combine=combine->next;
    26             }
    27         }
    28         while(l1!=NULL){
    29             combine->next=l1;
    30             l1=l1->next;
    31             combine=combine->next;
    32         }
    33         while(l2!=NULL){
    34             combine->next=l2;
    35             l2=l2->next;
    36             combine=combine->next;
    37         } 
    38     return dummyhead->next;}
    39 };

    最后一个链表循环完毕后其实可以直接把第二个链表接在后面,不需要再循环了。

    或者采用递归的方法,需要消耗更多的栈空间。

     1 class Solution {
     2 public:
     3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
     4         if (l1 == nullptr) {
     5             return l2;
     6         } else if (l2 == nullptr) {
     7             return l1;
     8         } else if (l1->val < l2->val) {
     9             l1->next = mergeTwoLists(l1->next, l2);
    10             return l1;
    11         } else {
    12             l2->next = mergeTwoLists(l1, l2->next);
    13             return l2;
    14         }
    15     }
    16 };
    17 
    18 作者:LeetCode-Solution
    19 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
    20 来源:力扣(LeetCode)
    21 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    Centos7.6部署rsyslog+loganalyzer+mysql日志管理服务器
    linux编程基础
    天融信防火墙NGFW4000,无法进入web管理和community属性查看
    H3C_IRF_BFD配置
    H3C_IRF_LACP配置
    H3C_IRF
    h3c_7506e引擎主备镜像同步
    cisco4507引擎模式切换
    usg6000
    vpdn1
  • 原文地址:https://www.cnblogs.com/rookiez/p/13197660.html
Copyright © 2011-2022 走看看