zoukankan      html  css  js  c++  java
  • 2.两数相加(Add Two Numbers) C++

    第一想法是顺着题目的原因,将两链表分别转化为一个数字,再将数字相加,然后把结果转化为字符串,存到答案链表中。但是数据太大会溢出!

    所以,要在计算一对数字的过程当中直接存储一个结果,注意结果大于9时进位,删去最终链表的最后一个节点。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            int carry=0;
            int x,y,z;
            ListNode* head = new ListNode(-1);
            ListNode* use = new ListNode(-1);
            ListNode* t = new ListNode(-1);
            head->next = t;
            while(l1 || l2)
            {
                if(!l1)
                {
                    x = 0;
                }else x = l1->val;
    
                if(!l2)
                {
                    y = 0;
                }else y = l2->val;
    
                z = x + y + carry;
                carry = 0;
                if(z>9)
                {
                    carry = 1;
                    z = z-10;
                }
                t->val = z;
                t->next = new ListNode(-1);
                use = t;
                t = t->next;
                t->next = NULL;
    
                if(l1)
                {
                    l1 = l1->next;
                }
                if(l2)
                {
                    l2 = l2->next;
                }
            }
            if(carry)
            {
                t->val = carry;
                t->next = new ListNode(-1);
                use = t;
                t = t->next;
                t->next = NULL;
            }
            t = head->next;
            use->next = NULL;
            return t;
        }
    };

     

  • 相关阅读:
    C/S模式客户端连接服务器连接不上的问题
    C#获取网络状态
    SQL2008R转SQL2005
    Centos7 调整磁盘空间
    crontab 定时任务
    nginx 简单教程
    vagrant 使用
    加快 hive 查询的 5 种方法
    编译 ambari 2.7.3
    kylin 连接 hortonworks 中的 hive 遇到的问题
  • 原文地址:https://www.cnblogs.com/tornado549/p/9937709.html
Copyright © 2011-2022 走看看