题目链接:https://leetcode.com/problems/add-two-numbers/

题目大意:将两个单链表对应的数字相加,注意进位,对应位得出的结果依然用单链表保存。

C++代码:

 

 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        ListNode *cur = new ListNode(0);
13         ListNode *fin = cur;
14         int sum = 0;
15         while(true)
16         {
17             if(l1 != NULL)
18             {
19                 sum += l1->val;
20                 l1 = l1->next;
21             }
22             if(l2 != NULL)
23             {
24                 sum += l2->val;
25                 l2 = l2->next;
26             }
27             cur->val = sum % 10;
28             sum /= 10;
29             if(l1 != NULL || l2 != NULL || sum != 0)
30             {
31                 cur->next = new ListNode(0);
32                 cur = cur->next;
33             }
34             else 
35                 break;
36         }
37         return fin;
38     }
39 };

 

Python代码:

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def addTwoNumbers(self, l1, l2):
 9         """
10         :type l1: ListNode
11         :type l2: ListNode
12         :rtype: ListNode
13         """
14         if l1 is None:
15             return l2
16         if l2 is None:
17             return l1
18         aa = ListNode(0)
19         bb = aa
20         sum = 0
21 
22         while(True):
23             if (l1):
24                 sum += l1.val
25                 l1 = l1.next
26             if (l2):
27                 sum += l2.val
28                 l2 = l2.next
29             aa.val = sum % 10
30             sum = sum / 10
31             if (l1 != None or l2 != None or sum != 0):
32                 aa.next = ListNode(0)
33                 aa = aa.next
34             else:
35                 break
36         return bb

 

posted on 2017-01-06 20:54  pangzp  阅读(220)  评论(0编辑  收藏  举报