题目描述:
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
思路:
1.另外新建一个链表用于存储结果,即开辟一个新链表的头节点head。建立一个while循环,循环条件是数字没处理完或处理完了还有进位。sum%10取得当前位的值,sum/=10得到进位的值。建立一个新节点last,使用last指向当前正在操作结点的前一个结点,首结点前面是NULL,如果我们操作的是首结点,结束后移动last。否则我们申请一个节点赋值,建立关系并且移动last。
C++代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head=new ListNode(0);
int sum=0;
ListNode* last=NULL;
while(l1!=NULL||l2!=NULL||sum!=0)
{
if(l1!=NULL)
{
sum+=l1->val;
l1=l1->next;
}
if(l2!=NULL)
{
sum+=l2->val;
l2=l2->next;
}
if(last!=NULL)
{
ListNode* temp=new ListNode(sum%10);
last->next=temp;
last=last->next;
}
else if(last==NULL)
{
head->val=sum%10;
last=head;
}
sum/=10;
}
return head;
}
};
思路一致但是超简练的一种写法--C++代码:
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode preHead(0), *p = &preHead;
int extra = 0;
while (l1 || l2 || extra) {
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
extra = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
return preHead.next;
}
};
2.递归的方法(本方法最快)
C++代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==NULL||l2==NULL)
{
return l1?l1:l2;
}
int sum=l1->val+l2->val;
int extra=sum/10;
ListNode* result=new ListNode(sum%10);
result->next=addTwoNumbers(l1->next, l2->next);
if(extra>0)
{
result->next=addTwoNumbers(new ListNode(extra),result->next);
}
return result;
}
};
3. 将两个链表中的数转换为整数,相加后再转换为链表返回,需要注意int型表示的范围,必要时需要使用long int或long long;
C++代码: