[leetcode]2. Add Two Numbers

来源:互联网 发布:初中免费课程软件 编辑:程序博客网 时间:2024/05/17 09:13

题目链接:https://leetcode.com/problems/add-two-numbers/#/description

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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

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



class Solution {  public:      ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {          // IMPORTANT: Please reset any member data you declared, as          // the same Solution instance will be reused for each test case.          if((l1==NULL)&&(l2==NULL)) {              return NULL;          }          int sum = 0;          ListNode *root = NULL;          ListNode *tail = NULL;          while(l1 != NULL || l2 != NULL) {              if (l1 != NULL) {                  sum += l1->val;                  l1 = l1->next;              }              if (l2 != NULL) {                  sum += l2->val;                  l2 = l2->next;              }              ListNode *p = new ListNode(sum % 10);              if (root == NULL) {                  root = p;                  tail = p;              } else {                  tail->next = p;                  tail = p;              }              sum = sum / 10;          }          if (sum != 0) {              ListNode *p = new ListNode(sum % 10);              if (root == NULL) {                  root = p;                  tail = p;              } else {                  tail->next = p;                  tail = p;              }          }          return root;      }  };