LeetCode OJ Add Two Numbers 链表求和

来源:互联网 发布:房地产端口可以退吗 编辑:程序博客网 时间:2024/06/05 16:22

Add Two Numbers

 Total Accepted: 49110 Total Submissions: 219893

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

/** * 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) {        ListNode result(0);        ListNode *p=&result;        int t=0;        int num1,num2,sum;        while(l1 || l2)        {            num1=(l1?l1->val:0);            num2=(l2?l2->val:0);            sum=num1+num2+t;            t=sum/10;            sum=sum%10;                        ListNode *pNew=new ListNode(sum);            p->next=pNew;            p=pNew;            if(l1)                l1=l1->next;            if(l2)                l2=l2->next;        }        if(t>0)        {            ListNode *pNew=new ListNode(t);            p->next=pNew;        }        return result.next;    }  };


0 0