LeetCode——002

来源:互联网 发布:线切割3b编程软件 编辑:程序博客网 时间:2024/06/05 22:38

这里写图片描述

/*/////////////////////////////////////////////////////////////////////////////2. Add Two Numbers My Submissions QuestionEditorial SolutionTotal Accepted: 135842 Total Submissions: 594541 Difficulty: MediumYou 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 -> 8Subscribe to see which companies asked this question/////////////////////////////////////////////////////////////////////////////*//** * 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) {        //如果有一条空,直接返回另一条就可以了,不需要再相加        if(l1==NULL)return l2;        if(l2==NULL)return l1;        ListNode* dummy=new ListNode(-1);        ListNode* p=dummy;        //进位变量        int carry=0;        while(l1 || l2){            int a=l1==NULL ? 0: l1->val;            int b=l2==NULL ? 0: l2->val;            int tmp=a+b+carry;            carry=tmp/10;            ListNode* N=new ListNode(tmp%10);            //链表指针后移            if(l1)l1=l1->next;            if(l2)l2=l2->next;            //结果链表指针后移            p->next=N;            p=N;        }        //判断是否仍有进位        if(carry){            p->next=new ListNode(carry);            p=p->next;        }        return dummy->next;    }};
0 0