题目描述:
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
我的做法,第一想法就是直接从左到右一边建立新链表一边把加的结果存进去,用一个t标记是否有进位。有一个小陷阱,就是当两个链表都加尽时有进位,我用最后一个if条件解决,注意看代码。
/**
* 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 * l=new ListNode(0);
ListNode * ll=l;
int t=0;
while(l1!=NULL||l2!=NULL){
if(l1!=NULL&&l2!=NULL){
int i=l1->val+l2->val;
l1=l1->next;
l2=l2->next;
if(i+t<10){
l->next=new ListNode(i+t);
l=l->next;
t=0;
}
else {
l->next=new ListNode(i+t-10);
l=l->next;
t=1;
}
}
if(l1!=NULL&&l2==NULL){
int i=l1->val;
l1=l1->next;
if(i+t<10){
l->next=new ListNode(i+t);
l=l->next;
t=0;
}
else {
l->next=new ListNode(i+t-10);
l=l->next;
t=1;
}
}
if(l1==NULL&&l2!=NULL){
int i=l2->val;
l2=l2->next;
if(i+t<10){
l->next=new ListNode(i+t);
l=l->next;
t=0;
}
else {
l->next=new ListNode(i+t-10);
l=l->next;
t=1;
}
}
if(l1==NULL&&l2==NULL){//陷阱,如果没有这里会出错
if(t){
l->next=new ListNode(t);
l=l->next;
t=0;
}
}
}
l=ll;
return l->next;
}
};