代码改变世界

Add Two Numbers

2015-03-30 10:32  笨笨的老兔子  阅读(155)  评论(0编辑  收藏  举报

给定两个链表,链表中的数字非负,这是将两个整数由链表表示,且逆序,求两个整数的和。
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
模拟题,对应位数相加,考虑一下链表长度不同,以及进位即可

  1. class Solution {
  2. public:
  3. ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  4. ListNode* res = new ListNode(0);
  5. ListNode* head = res;
  6. int carry = 0, tmpl1 = 0, tmpl2 = 0, tmpRes = 0;
  7. while (carry || l1 || l2)
  8. {
  9. tmpl1 = 0;
  10. tmpl2 = 0;
  11. if (l1)
  12. {
  13. tmpl1 = l1->val;
  14. l1 = l1->next;
  15. }
  16. if (l2)
  17. {
  18. tmpl2 = l2->val;
  19. l2 = l2->next;
  20. }
  21. tmpRes = tmpl1 + tmpl2 + carry;
  22. head->next = new ListNode(tmpRes % 10);
  23. carry = tmpRes / 10;
  24. head = head->next;
  25. }
  26. return res->next;
  27. }
  28. };