题目概述:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1、创建一个新链表,并分别使用三个指针指向三个链表,新建一个整型变量来存放进位值;
2、只要分别指向l1和l2的指针p1、p2不为空指针,就将值同之前的进位值相加;
3、所得的和%10赋给p3,所得的和/10来判断下一位是否有进位;
4、最后如果p1和p2都为空,但仍有进位,则新建一个节点保存进位值。
注意:p1=p1->next;p2=p2->next;操作前要先判断是否为空指针。
/**
* 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* dummy=new ListNode(0);
ListNode* p1=l1;
ListNode* p2=l2;
ListNode* p3=dummy;
int carry=0;
while(p1!=nullptr||p2!=nullptr)
{
int p1_val=(p1==nullptr)?0:p1->val;
int p2_val=(p2==nullptr)?0:p2->val;
p3->val=(p1_val+p2_val+carry)%10;
if((p1_val+p2_val+carry)/10==1)
carry=1;
else
carry=0;
if(p1!=nullptr)
p1=p1->next;
if(p2!=nullptr)
p2=p2->next;
if(p1!=nullptr||p2!=nullptr||carry!=0)
{
p3->next=new ListNode(carry);
p3=p3->next;
}
}
return dummy;
}
};
/**
* 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 *ptr=head;
int carry=0;
while(true){
if(l1!=NULL)
{
carry+=l1->val;
l1=l1->next;
}
if(l2!=NULL)
{
carry+=l2->val;
l2=l2->next;
}
ptr->val=carry%10;
carry=carry/10;
if(l1!=NULL||l2!=NULL||carry!=0)
{
ptr->next=new ListNode(0);
ptr=ptr->next;
}
else
break;
}
return head;
}
};
这里的更详细,思路更清晰:https://leetcode.com/problems/add-two-numbers/solution/