【Leetcode】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

【代码】

/**
 * 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 *l3=new ListNode(0);
    ListNode *p3=l3;
    if(NULL==l1){
        return l2;
    }
    else if(NULL==l2){
        return l1;
    }
    ListNode *p1=l1;
    ListNode *p2=l2;
    int carry=0;
    while(p1&&p2){
        int sum=p1->val+p2->val+carry;
        carry=sum/10;
        sum=sum-carry*10;
        ListNode *newNode=new ListNode(sum);
        p3->next=newNode;
        p3=p3->next;
        p1=p1->next;
        p2=p2->next;
    }
    while(p1){
        int sum=p1->val+carry;
        carry=sum/10;
        sum=sum-carry*10;
        ListNode *newNode=new ListNode(sum);
        p3->next=newNode;
        p3=p3->next;
        p1=p1->next;
    }
    while(p2){
        int sum=p2->val+carry;
        carry=sum/10;
        sum=sum-carry*10;
        ListNode *newNode=new ListNode(sum);
        p3->next=newNode;
        p3=p3->next;
        p2=p2->next;
    }
    if(carry){
        ListNode *newNode=new ListNode(carry);
        p3->next=newNode;
    }
    return l3->next;
    }
};

【总结】

1.结构体ListNode的构造函数ListNode(int x) : val(x), next(NULL) {}

   C++中结构体struct和类class类似,也可以有构造函数和析构函数等,区别在于:第一,成员变量和成员函数的默认访问级别不一样,struct中默认是public,class中默认是private;第二,默认继承方式不一样,struct默认是public,class默认是private

2.注意边界条件的考虑:入参指针空指针判断;链表长度不一样的时候的处理;链表遍历完后最后一个进位的考虑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值