Chinaunix首页 | 论坛 | 博客
  • 博客访问: 622757
  • 博文数量: 79
  • 博客积分: 848
  • 博客等级: 军士长
  • 技术积分: 1800
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-26 19:30
文章分类

全部博文(79)

文章存档

2015年(4)

2013年(39)

2012年(36)

分类: C/C++

2015-04-14 16:57:00

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


需要注意的是进位和指针操作!

点击(此处)折叠或打开

  1. /**
  2.  * Definition for singly-linked list.
  3.  * struct ListNode {
  4.  * int val;
  5.  * ListNode *next;
  6.  * ListNode(int x) : val(x), next(NULL) {}
  7.  * };
  8.  */
  9. class Solution {
  10. public:
  11.     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
  12.     ListNode *result = l1;
  13.     ListNode *p1 = l1;
  14.     ListNode *p2 = l2;
  15.     ListNode *pre = l1;
  16.     int s = 0;
  17.     while (p1 && p2) {
  18.         pre = p1;
  19.         int temp = s;
  20.         s = (p1->val + p2->val + s) / 10;
  21.         p1->val = (p1->val + p2->val + temp) % 10;
  22.         p1 = p1->next;
  23.         p2 = p2->next;
  24.     }
  25.     if (p2) {
  26.      pre->next = p2;
  27.         p1 = p2;
  28.     }
  29.     while (p1) {
  30.         pre = p1;
  31.         if (s != 0) {
  32.             int temp = s;
  33.             s = (p1->val + s) / 10;
  34.             p1->val = (p1->val + temp) % 10;
  35.             p1 = p1->next;
  36.         } else {
  37.             break;
  38.         }
  39.     }
  40.     if (s) {
  41.         pre->next = new ListNode(s);
  42.     }
  43.     return result;
  44.     }
  45. };


阅读(3162) | 评论(0) | 转发(0) |
0

上一篇:leetCode算法题目之我解(1)Two Sum

下一篇:没有了

给主人留下些什么吧!~~