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.
我的代码:
/**
* 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,*ans,*p;
ans=new ListNode(l1->val+l2->val);
head=ans;
int pan=0,cishu=0,a,pan1=1;
do
{
if(ans->val>=10)
{
ans->val-=10;
pan=1;
}
if(l1->next==NULL&&l2->next==NULL)
{
if(pan==1){a=1;}
else{pan1=0;}
}
if(l1->next!=NULL&&l2->next!=NULL)
{l1=l1->next;
l2=l2->next;
a=(l1->val)+(l2->val);
}
if(l1->next==NULL&&l2->next!=NULL)
{
l2=l2->next;
a=l2->val;
}
if(l1->next!=NULL&&l2->next==NULL)
{
l1=l1->next;
a=l1->val;
}
if(pan1)
p=new ListNode(a);
if(pan)
{
p->val+=1;
}
pan=0;
ans->next=p;
ans=ans->next;
cishu++;
}
while(l1->next!=NULL||l2->next!=NULL);
return head;
}
};
个人理解:
运用了加法器的原理,对链表进行逐个相加并判断,但是代码还可以精化,还又很大的优化空间。