leetcode 之Single Number(14)

 这题并不难,但需要注意细节。

 ListNode* addTwo(ListNode *l1, ListNode *l2)
      {
          ListNode dummy(-1);
          int carry = 0;
          ListNode *prev = &dummy;

          for (ListNode *pa = l1, *pb = l2; pa != nullptr || pb != nullptr; 
              pa = pa == nullptr ? nullptr : pb->next, pb = pb == nullptr ? nullptr : pb->next,prev=prev->next)
          {
              int ai = pa == nullptr ? 0 : pa->val;
              int bi = pb == nullptr ? 0 : pb->val;

              int value = (ai + bi + carry) % 10;
              carry = (ai + bi + carry) / 10;

              prev->next = new ListNode(carry);

          }

          if (carry > 0)
              prev->next = new ListNode(carry);

          return dummy.next;
      }
View Code

 

posted @ 2016-05-18 14:00  牧马人夏峥  阅读(79)  评论(0编辑  收藏  举报