码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode --- Add Two Numbers

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

标签:style   c   class   blog   code   java   

题目链接

说来算是个基础题目,可是还是各种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

标签:style   c   class   blog   code   java   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!