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

Leetcode#2 Add Two Numbers

时间:2015-01-30 19:13:02      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

基本链表操作

 

代码:

 1 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
 2         ListNode *h = NULL;
 3         ListNode *t = NULL;
 4         int carry = 0;
 5         
 6         while (l1 && l2) {
 7             ListNode *node = new ListNode((l1->val + l2->val + carry) % 10);
 8             carry = (l1->val + l2->val + carry) / 10;
 9             if (!h)
10                 h = t = node;
11             else {
12                 t->next = node;
13                 t = t->next;
14             }
15             l1 = l1->next;
16             l2 = l2->next;
17         }
18         while (l1) {
19             ListNode *node = new ListNode((l1->val + carry) % 10);
20             carry = (l1->val + carry) / 10;
21             if (!h)
22                 h = t = node;
23             else {
24                 t->next = node;
25                 t = t->next;
26             }
27             l1 = l1->next;
28         }
29         while (l2) {
30             ListNode *node = new ListNode((l2->val + carry) % 10);
31             carry = (l2->val + carry) / 10;
32             if (!h)
33                 h = t = node;
34             else {
35                 t->next = node;
36                 t = t->next;
37             }
38             l2 = l2->next;
39         }
40         if (carry > 0)
41             t->next = new ListNode(carry);
42             
43         return h;
44 }

 

Leetcode#2 Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/boring09/p/4262863.html

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