【题目】
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.注意边界条件的考虑:入参指针空指针判断;链表长度不一样的时候的处理;链表遍历完后最后一个进位的考虑。