题目描述:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
*思路:
遍历两个链表,判断两数相加是否有进位。
遍历结束,判断那个链表没结束,继续遍历。
遍历完成再次判断剩余进位,决定是否补个1.
代码
/**
* 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* res=new ListNode(0);
ListNode* ptr=res;
int adding=0;
while(l1!=NULL && l2!=NULL){
int temp=l1->val + l2->val+adding;
if (temp<10){
ListNode* t=new ListNode(temp);
ptr->next=t;
adding=0;
}
else{
ListNode* t=new ListNode(temp%10);
ptr->next=t;
adding=1;
}
ptr=ptr->next;
l1=l1->next;
l2=l2->next;
}
while(l1!=NULL){
int temp=l1->val + adding;
if(temp<10){
ListNode* t=new ListNode(temp);
ptr->next=t;
adding=0;
}
else{
ListNode* t=new ListNode(temp%10);
ptr->next=t;
adding=1;
}
ptr=ptr->next;
l1=l1->next;
}
while(l2!=NULL){
int temp=l2->val + adding;
if(temp<10){
ListNode* t=new ListNode(temp);
ptr->next=t;
adding=0;
}
else{
ListNode* t=new ListNode(temp%10);
ptr->next=t;
adding=1;
}
ptr=ptr->next;
l2=l2->next;
}
if(adding==1){
ListNode* t=new ListNode(1);
ptr->next=t;
}
return res->next;
}
};
拜拜