【leetcode】两数相加(Add Two Numbers)【C++】

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/qq_34018840/article/details/89116302

题目如下:

解题思路:

      本题按照顺序便利两个链表,逐位相加。需要注意的是:两数相加的溢出需要进位,另外不要忘掉最后一次进位。

      代码如下(C++):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode * head = new ListNode(0);
        ListNode * p = head;
        //用于保存当前累加值
        int count = 0;
        while(l1 != NULL || l2 != NULL){
            count /= 10;
            if(l1 != NULL){
                count = count + l1->val;
                l1 = l1->next;
            }
            if(l2 != NULL){
                count = count + l2->val;
                l2 = l2->next;
            }
            // 创建下一个节点并指向它
            p->next = new ListNode(count % 10);
            p = p->next;
        }
        //处理最后一个进位
        if(count > 9){
            p->next = new ListNode(1);
        }
        
        return head->next;
    }
};

 

猜你喜欢

转载自blog.csdn.net/qq_34018840/article/details/89116302