题目描述:
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
/**
* 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) {
int digit_Num,extra_Num=0,random;
ListNode *tou=NULL,*p1,*p2,*temp;
while(l1!=NULL&&l2!=NULL){
digit_Num = (l1->val+l2->val+extra_Num)%10;
//cout<<"digit_Num = "<<digit_Num<<endl;
if(tou==NULL){
//new malloc还是有相似的地方
//p2 = p1=tou = new ListNode(digit_Num+extra_Num);
p2 = p1 = tou =(ListNode*)new ListNode(digit_Num+extra_Num);
//cout<<"tou "<<tou->val<<endl;
}else{
p1 = (ListNode*)new ListNode(digit_Num);
p2->next = p1;
p2 = p1;
}
extra_Num = (l1->val+l2->val+extra_Num)/10;
//cout<<"extra_Num = "<<extra_Num<<endl;
//temp = l1;
l1 = l1->next;
//free(temp);
//temp = l2; 可能是栈上的内存 不能瞎释放
//free(temp);
l2 = l2->next;
}
//cout<<" Here extra_Num = "<<extra_Num<<endl;
if(l1==NULL&&l2==NULL){
//cout<<"3 code here"<<"ex = "<<extra_Num<<endl;
if(extra_Num!=0)
p2->next = (ListNode*)new ListNode(extra_Num);
}else if(l1==NULL){
temp = l2;
while(temp!=NULL&&extra_Num!=0)
{
random = temp->val;
//cout<<"temp->val = "<<temp->val<<endl;
temp->val = (extra_Num + temp->val)%10;
// cout<<"temp->val = "<<temp->val<<endl;
extra_Num = (extra_Num+random)/10;
temp = temp->next;
}
//cout<<"ex = "<<extra_Num<<endl;
if(extra_Num!=0){
temp = l2;
//cout<<"1 Code come to here"<<endl;
while(temp->next!=NULL)
temp = temp->next;
temp->next = (ListNode*)new ListNode(extra_Num);
}
p2->next = l2;
}else if(l2==NULL){
temp = l1;
while(temp!=NULL&&extra_Num!=0)
{
random = temp->val;
temp->val = (extra_Num + temp->val)%10;
extra_Num = (extra_Num+random)/10;
temp = temp->next;
}
// cout<<"ex = "<<extra_Num<<endl;
if(extra_Num!=0){
temp = l1;
// cout<<"2 Code come to here"<<endl;
while(temp->next!=NULL)
temp = temp->next;
temp->next = (ListNode*)new ListNode(extra_Num);
}
p2->next = l1;
}
return tou;
}
};
无限大的数字相加问题,一般会模拟加法运算,同时利用栈来提高效率,本题是一样的,倒序存放的链表和栈是一样的,操作复杂了一点,以上代码可以做一点优化,但是算法本身没有办法提速。
能不动手尽量不动手,在大脑中模拟算法的计算步骤和流程,最好在脑子中写好之后再动手,否则无法提高,只是根据OJ判定的数据来填漏洞而已,太笨了。