您的位置:首页 > 其它

Add Two Numbers(medium)

2016-09-04 15:36 393 查看
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

我的解答:

class Solution {

public:

 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

  int n = 0;

  ListNode* a = NULL;

  ListNode* current = NULL;

  if ((l1->val + l2->val) >= 10) {

   n = 1;

   a = new ListNode(l1->val + l2->val - 10);

  }

  else {

   a = new ListNode(l1->val + l2->val);

  }

  current = a;

  l1 = l1->next;

  l2 = l2->next;

  while (l1 != NULL || l2 != NULL||n==1) {

   if (l1 == NULL&&l2 == NULL) {

    current->next = new ListNode(1);

    n = 0;

   }

   else if (l1 == NULL) {

    if (l2->val + n >= 10) {

     current->next = new ListNode(l2->val + n - 10);

     current = current->next;

     n = 1;

    }

    else {

     current->next = new ListNode(l2->val + n);

     current = current->next;

     n = 0;

    }

    l2 = l2->next;

   }

   else if (l2 == NULL) {

    if (l1->val + n >= 10) {

     current->next = new ListNode(l1->val + n - 10);

     current = current->next;

     n = 1;

    }

    else {

     current->next = new ListNode(l1->val + n);

     current = current->next;

     n = 0;

    }

    l1 = l1->next;

   }

   else {

    if (l1->val + l2->val+n >= 10) {

     current->next = new ListNode(l1->val + l2->val + n-10);

     current = current->next;

     n = 1;

    }

    else {

     current->next = new ListNode(l1->val + l2->val + n);

     current = current->next;

     n = 0;

    }

    l1 = l1->next;

    l2 = l2->next;

   }
  }

  return a;

 }

};

这题的内容就是利用列表来存储两个整数让后相加,将结果放到另外一个列表中,我采用的方法是用一个int变量n来储存是否需要进位,让后对提供的两个列表逐项相加(包括与n),然后同时指向下一项,储存的时候将每次的结果都用new一个结构体来储存。其中每次相加考虑的情况是两个都没到最后一项,两个中某一个到最后一项,两个都到最后一项但有进位。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: