Shirlies
宁静专注认真的程序媛~

题目:

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

样例:

给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null

答案:

从头到尾按链表顺序遍历相加就行啦,如果加到最后,进位不为0,还需要另外添加一个节点。

代码:

 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     /**
12      * @param l1: the first list
13      * @param l2: the second list
14      * @return: the sum list of l1 and l2 
15      */
16     ListNode *addLists(ListNode *l1, ListNode *l2) {
17         // write your code here
18         int carry = 0,value = 0;
19         ListNode *l1Iter = l1;
20         ListNode *l2Iter = l2;
21         ListNode *ansRoot = NULL,*ansIter = NULL;
22         
23         while(l1Iter != NULL && l2Iter != NULL)
24         {
25             value = l1Iter->val + l2Iter->val + carry;
26             carry = value / 10;
27             value = value % 10;
28             
29             ListNode *node = new ListNode(value);
30             if(ansRoot == NULL)
31             {
32                 ansRoot = node;
33             }
34             
35             if(ansIter != NULL)
36             {
37                 ansIter->next = node;
38             }
39             
40             ansIter = node;
41             l1Iter = l1Iter->next;
42             l2Iter = l2Iter->next;
43         }
44         
45         while(l1Iter != NULL)
46         {
47             value = l1Iter->val + carry;
48             carry = value / 10;
49             value = value % 10;
50             
51             ListNode *node = new ListNode(value);
52             if(ansRoot == NULL)
53             {
54                 ansRoot = node;
55             }
56             
57             if(ansIter != NULL)
58             {
59                 ansIter->next = node;
60             }
61             
62             ansIter = node;
63             l1Iter = l1Iter->next;
64         }
65         
66         while(l2Iter != NULL)
67         {
68             value = l2Iter->val + carry;
69             carry = value / 10;
70             value = value % 10;
71             
72             ListNode *node = new ListNode(value);
73             if(ansRoot == NULL)
74             {
75                 ansRoot = node;
76             }
77             
78             if(ansIter != NULL)
79             {
80                 ansIter->next = node;
81             }
82             
83             ansIter = node;
84             l2Iter = l2Iter->next;
85         }
86         
87         if(carry != 0)
88         {
89             ListNode *node = new ListNode(carry);
90             if(ansIter != NULL)
91             {
92                 ansIter->next = node;
93             }
94         }
95         return ansRoot;
96     }
97 };
View Code

 

posted on 2016-02-26 09:48  Shirlies  阅读(2478)  评论(0编辑  收藏  举报