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 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    2017-2018-1 20155334第八周课堂实践总结+课下作业+教材内容总结
    移动手机号段区别
    使用Maven搭建Hadoop开发环境
    RunMR.java
    BeanUtils内省工具包
    eclipse和myeclipse中如何关闭自动补全括号,花括号,双引号等功能
    为什么在jsp中写${pageContext.request.contextPath }失效了
    开发WEB项目的步骤
    MVC的职责分工
    关于import中使用*号是否会影响程序性能
  • 原文地址:https://www.cnblogs.com/rookiez/p/13197660.html
Copyright © 2011-2022 走看看