您的位置:首页 > 其它

2. Add Two Numbers

2016-04-10 10:20 246 查看
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

Subscribe to see which companies asked this question

题目分析:

这个题目的意思是输入是两个list,每个list代表的是一个数,list的每个节点值为这个数从低位到高位的值。

比如(2 -> 4 -> 3)表示的是342;(5 -> 6 -> 4)表示的是465.求这两个数的合,以同样的格式输出。

弄清楚题目就很好做了,每一位都按照加法的规则加上去就可以了。

代码:

/**

 * 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;

        ListNode * p1=new ListNode(0);

        ListNode * head=p1;

        while(l1 || l2 || (carry!=0))

        {

            int t1=0,t2=0;

            if(l1)

            {

                t1=l1->val;

                l1=l1->next;

            }

            if(l2)

            {

                t2=l2->val;

                l2=l2->next;

            }

            int t=t1+t2+carry;

            carry=t/10;

            ListNode * p2=new ListNode(t%10);

            p1->next=p2;

            p1=p2;

        }

        p1->next=NULL;

        return head->next;

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  list