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

    简介

    用了一个比较复杂的方法, 直接讲两个链表的数据取出来,使用vector进行排序, 然后再链接两个链表, 在把数据插回去. 不如递归简单.

    code

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */
    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            ListNode *p = l1;
            ListNode *q = l2;
            if(p == nullptr && q == nullptr){
                return p;
            }
            // 将p插入q中
            vector<int> v;
            while(p){
                v.push_back(p->val);
                p = p->next;
            }
            while(q){
                v.push_back(q->val);
                q = q->next;
            }
            sort(v.begin(), v.end());
            if(l1 != nullptr){
                 p = l1;
                 while(p->next){
                    p = p->next;
                }
                p->next = l2;
                p = l1;
                int i=0;
                while(p){
                    p->val = v[i];
                    i++;
                    p = p->next; 
                }
                return l1;
            }else{
                q = l2;
                 while(q->next){
                    q = q->next;
                }
                q->next = l1;
                q = l2;
                int i=0;
                while(q){
                    q->val = v[i];
                    i++;
                    q = q->next; 
                }
                return l2;
            }
            return nullptr;
    
            
        }
    };
    
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null){
                return l2;
            } else if(l2 == null){
                return l1;
            } else if(l1.val < l2.val){
                l1.next = mergeTwoLists(l1.next, l2);
                return l1;
            } else{
                l2.next = mergeTwoLists(l1, l2.next);
                return l2;
            }
        }
    }
    

    TIPS

    递归算法很巧妙, 不用构造零时指针. 及其方便

    Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
  • 相关阅读:
    js-jQuery对象与dom对象相互转换
    django模板{%for%}中的forloop的应用
    ubuntu MySQL数据库输入中文乱码 解决方案
    多线程下的神奇的IOCP
    类库服务寄宿到WebHost
    细说Asp.Net WebAPI消息处理管道
    项目发布Debug和Release版的区别
    linux yum命令详解
    Linux系统如何查看版本信息
    Linux查看物理CPU个数、核数、逻辑CPU个数
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/14800556.html
Copyright © 2011-2022 走看看