You are given two non-empty linked lists representing two non-negative integers. 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.node
You may assume the two numbers do not contain any leading zero, except the number 0 itself.git
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8code
就是按照咱们小时候的竖式加法的方式来计算就能够了。不一样的是,这里的进位是向右进位;而咱们小时候计算加法的进位是向左进位。it
class Solution { public: ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode* p = l1; ListNode* q = l2; int sum = 0; ListNode* sentinel = new ListNode(0); ListNode* d = sentinel; if ((p == NULL) && (q != NULL)) { return q; } if ((p != NULL) && (q == NULL)) { return p; } do { if (p != NULL) { sum += (p->val); p = p->next; } else { sum += 0; // p = p->next; } if (q != NULL) { sum += (q->val); q = q->next; } else { sum += 0; // q = q->next; } d->next = new ListNode((sum % 10)); d = d->next; sum = (sum/10); if(q==NULL && q==NULL && sum!=0) { d->next=new ListNode(sum); } }while (p != NULL || q != NULL); return sentinel->next; } };