首页 > 其他 > 详细

LeetCode --- Add Two Numbers

时间:2014-05-28 23:55:05      阅读:596      评论:0      收藏:0      [点我收藏+]

题目链接

说来算是个基础题目,可是还是各种CE,各种WA,基础还是不扎实。

附上代码:

bubuko.com,布布扣
 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         if (l1 == NULL) return l2;
13         if (l2 == NULL) return l1;
14         // q: keep trace of the linked list that has been produced as the answer
15         // ll1: keep trace of l1
16         // ll2: keep trace of l2
17         ListNode *head(NULL), *q(NULL), *ll1 = l1, *ll2 = l2;
18         // c: holds the carry digit 
19         int c = 0;
20         while (ll1!=NULL || ll2!=NULL) {
21             // sum: holds sum of ll1->val, ll2->val and c
22             int sum = 0;
23             if (ll1 != NULL) {
24                 sum += ll1->val;
25                 ll1 = ll1->next;
26             }
27             if (ll2 != NULL) {
28                 sum += ll2->val;
29                 ll2 = ll2->next;
30             }
31             sum += c;
32             ListNode *p = new ListNode(sum%10);
33             c = sum >= 10 ? 1 : 0;
34             if (head == NULL) {
35                 head = q = p;
36             } else {
37                 q->next = p;
38                 q = p;
39             }
40         }
41         if (c) {
42             q->next = new ListNode(c);
43         }
44         return head;
45     }
46 };
bubuko.com,布布扣

 

LeetCode --- Add Two Numbers,布布扣,bubuko.com

LeetCode --- Add Two Numbers

原文:http://www.cnblogs.com/Stomach-ache/p/3754409.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!