[LeetCode-2] Add Two Numbers

Add Two Numbers

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

 

破题,就是困了,居然也写了好多分钟……睡觉了……(~﹃~)~zZ

 

 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         ListNode *result = NULL, *tmp_node = NULL, *new_node = NULL;
15         ListNode *tmp_l1 = l1, *tmp_l2 = l2;
16         if (NULL == l1 && NULL == l2) {
17             return NULL;
18         }
19         int ext = 0;
20         
21         while (NULL != tmp_l1 && NULL != tmp_l2) {
22             if (NULL == result) {
23                 result = new ListNode((tmp_l1->val + tmp_l2->val) % 10);
24                 ext = (tmp_l1->val + tmp_l2->val) / 10;
25                 tmp_node = result;
26                 tmp_l1 = tmp_l1->next;
27                 tmp_l2 = tmp_l2->next;
28                 continue;
29             }
30             new_node = new ListNode((tmp_l1->val + tmp_l2->val + ext) % 10);
31             ext = (tmp_l1->val + tmp_l2->val + ext) / 10;
32             tmp_node->next = new_node;
33             tmp_node = tmp_node->next;
34             tmp_l1 = tmp_l1->next;
35             tmp_l2 = tmp_l2->next;
36         }
37         
38         while (NULL != tmp_l1) {
39             if (NULL == result) {
40                 result = new ListNode(tmp_l1->val);
41                 ext = 0;
42                 tmp_node = result;
43                 tmp_l1 = tmp_l1->next;
44                 continue;
45             }
46             new_node = new ListNode((tmp_l1->val + ext) % 10);
47             ext = (tmp_l1->val + ext) / 10;
48             tmp_node->next = new_node;
49             tmp_node = tmp_node->next;
50             tmp_l1 = tmp_l1->next;
51         }
52         while (NULL != tmp_l2) {
53             if (NULL == result) {
54                 result = new ListNode(tmp_l2->val);
55                 ext = 0;
56                 tmp_node = result;
57                 tmp_l2 = tmp_l2->next;
58                 continue;
59             }
60             new_node = new ListNode((tmp_l2->val + ext) % 10);
61             ext = (tmp_l2->val + ext) / 10;
62             tmp_node->next = new_node;
63             tmp_node = tmp_node->next;
64             tmp_l2 = tmp_l2->next;
65         }
66         if (ext > 0) {
67             new_node = new ListNode(ext);
68             tmp_node->next = new_node;
69         }
70         return result;
71     }
72 };
View Code

 

posted on 2013-08-20 23:35  似溦若岚  阅读(126)  评论(0编辑  收藏  举报

导航