LeetCode 2 - Add Two Numbers

来源:互联网 发布:js遍历json数组对象 编辑:程序博客网 时间:2024/05/16 17:44

问题简述

  1. Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

我的解答

这是一道很简单的题。

思路很直接,就像笔算加法一样,从最低位开始一位位计算,不过要注意进位的处理。另外,一开始也要初始化两个指针head和tail,前者用来作为最后返回的答案,后者是用来不断修改链表的。

#include <iostream>#include <vector>#include <list>#include <algorithm>#include <cmath>using namespace std;class Solution {public:    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)    {        int carry=0;        ListNode *head=NULL,*tail=NULL;        if(l1==NULL&&l2==NULL)        {            //Nothing        }        else if(l1==NULL)        {            head=new ListNode(l2->val);            tail=head;            l2=l2->next;        }        else if(l2==NULL)        {            head=new ListNode(l1->val);            tail=head;            l1=l1->next;        }        else        {            auto sum=l1->val+l2->val;            if(sum>=10)            {                sum-=10;                carry=1;                head=new ListNode(sum);                tail=head;            }            else            {                head=new ListNode(sum);                tail=head;            }            l1=l1->next;            l2=l2->next;        }        while (1)        {            if(l1==NULL&&l2==NULL)            {                if(carry)                    tail->next=new ListNode(carry);                tail=tail->next;                break;            }            else if(l1==NULL)            {                auto sum=l2->val+carry;                carry=0;                if(sum>=10)                {                    carry=1;                    sum-=10;                }                tail->next=new ListNode(sum);                tail=tail->next;                l2=l2->next;            }            else if(l2==NULL)            {                auto sum=l1->val+carry;                carry=0;                if(sum>=10)                {                    carry=1;                    sum-=10;                }                tail->next=new ListNode(sum);                tail=tail->next;                l1=l1->next;            }            else            {                auto sum=l1->val+l2->val+carry;                carry=0;                if(sum>=10)                {                    sum-=10;                    carry=1;                    tail->next=new ListNode(sum);                    tail=tail->next;                }                else                {                    tail->next=new ListNode(sum);                    tail=tail->next;                }                l1=l1->next;                l2=l2->next;            }        }        return head;    }};
0 0
原创粉丝点击