[LeetCode]Add Two Numbers

题意:链表大数的加法处理,不过链表上的数是反序的。

本题来源:https://leetcode.com/problems/add-two-numbers/

分析:

1.如果其中链表为空,则不用计算了;如果两个链表都为空,则返回空(链表不熟)。

 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         
15         int carry = 0;
16         ListNode* tail = new ListNode(0);
17         ListNode* ptr = tail;
18         
19         while(l1 != NULL || l2 != NULL){
20             int val1 = 0;
21             if(l1 != NULL){
22                 val1 = l1->val;
23                 l1 = l1->next;
24             }
25             
26             int val2 = 0;
27             if(l2 != NULL){
28                 val2 = l2->val;
29                 l2 = l2->next;
30             }
31             
32             int tmp = val1 + val2 + carry;
33             ptr->next = new ListNode(tmp % 10);
34             carry = tmp / 10;
35             ptr = ptr->next;
36         }
37         if(carry == 1)ptr->next = new ListNode(1);
38         return tail->next;
39     }
40 };

 

你可能感兴趣的:(LeetCode)