Leetcode 2 Add Two Numbers
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。
开始的时候,我声明单链表写的是ListNode* ans=(ListNode * )malloc(sizeof(ListNode));在线调试,闭着眼睛都能跑过后台数据,一直报RE,后来改成ListNode* ans=new ListNode(0);就过了。
代码
/**
* 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* ptr=new ListNode(0);
ListNode* ans=ptr;
while(l1&&l2)
{
int tmp=(l1->val)+(l2->val);
ListNode* p=new ListNode(0);
p->val=tmp;
p->next=NULL;
ptr->next=p;
ptr=ptr->next;
l1=l1->next;
l2=l2->next;
}
ans=ans->next;
if(l1) ptr->next=l1;
else ptr->next=l2;
ListNode *car=ans,*last=ans;
int carry=0;
while(car)
{
car->val=car->val+carry;
if((car->val)>=10)
{
car->val-=10;
carry=1;
}
else carry=0;
last=car;
car=car->next;
}
if(carry) {
ListNode* p=new ListNode(0);
p->val=1;
p->next=NULL;
last->next=p;
}
return ans;
}
};