zoukankan      html  css  js  c++  java
  • leecode第二题(两数相加)

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    #include <iostream>
    using namespace std;
    
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    
            if ((l1 == NULL) && (l2 == NULL))
            {
                cout << "Invalid input!";
                return NULL;
            }
    
            ListNode* fir = l1;
            ListNode* sec = l2;
            ListNode* p = new ListNode(0);
            ListNode* thr = p;//为了不干预原指针,我分别设了fir,sec,thr三个临时指针
    
            while (fir != NULL || sec != NULL)
            {
                int a = 0, b = 0;//分别检查fir,sec
                if (fir != NULL)
                {
                    a = fir->val;
                    fir = fir->next;
                }
                if (sec != NULL)
                {
                    b = sec->val;
                    sec = sec->next;
    
                }
    
                ListNode* cur = new ListNode(0);//设了个新节点
                cur->val = (thr->val + a + b) / 10;
                thr->val = (thr->val + a + b) % 10;
                if (fir == NULL && sec == NULL && cur->val == 0)//如果接下来没有数要加了,那就是最顶位为0,为了不让显示,我就直接跳出了,这个事当时恶心到我了
                    break;
                thr->next = cur;
                thr = cur;
            }
    
            return p;
    
        }
    };

    分析:

    考察链表和编程能力

    这个时间复杂度为O(max(m,n)),空间复杂度也是O(max(m,n))

    总结:

    编程还是不够熟练,循环里两个if没有第一时间想到,还有为了让顶位为0不显示,我居然写了好几遍,尴尬。

  • 相关阅读:
    利用dockerfile定制镜像
    发布Docker 镜像到dockerhub
    Docker 停止容器
    133. Clone Graph
    132. Palindrome Partitioning II
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    127. Word Ladder
  • 原文地址:https://www.cnblogs.com/CJT-blog/p/10571463.html
Copyright © 2011-2022 走看看