标签:
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(l1==NULL&&l2==NULL) return NULL; if(l1==NULL&&l2!=NULL) return l2; if(l1!=NULL&&l2==NULL) return l1; ListNode*p1,*p2,*head,*p,*s; p1=l1; p2=l2; int flag=0; head=(ListNode*)malloc(sizeof(ListNode)); p=head; while(p1&&p2) { s=(ListNode*)malloc(sizeof(ListNode)); flag=flag+p1->val+p2->val; if(flag>9) { s->val=flag-10; flag=1; } else { s->val=flag; flag=0; } p->next=s; p=s; p1=p1->next; p2=p2->next; } if(!p1&&!p2) { if(flag==1) { s=(ListNode*)malloc(sizeof(ListNode)); s->val=flag; p->next=s; p=s; } } else { ListNode* temp; if(!p1&&p2) temp=p2; else temp=p1; while(temp) { s=(ListNode*)malloc(sizeof(ListNode)); flag=flag+temp->val; if(flag>9) { s->val=flag-10; flag=1; } else { s->val=flag; flag=0; } p->next=s; p=s; temp=temp->next; } if(flag==1) { s=(ListNode*)malloc(sizeof(ListNode)); s->val=flag; p->next=s; p=s; } } head=head->next; p->next=NULL; return head; }
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(l1==NULL&&l2==NULL) return NULL; if(l1==NULL&&l2!=NULL) return l2; if(l1!=NULL&&l2==NULL) return l1; unsigned long n=0; unsigned long m=0; ListNode*p1,*p2,*head,*p,*s; p1=l1; p2=l2; int i=0; while(p1) { n+=(p1->val*pow(10.0,i)); i++; p1=p1->next; } i=0; while(p2) { m+=(p2->val*pow(10.0,i)); i++; p2=p2->next; } unsigned long res=n+m; head=(ListNode*)malloc(sizeof(ListNode)); p=head; if(res==0) { s=(ListNode*)malloc(sizeof(ListNode)); s->val=res; p->next=s; p=s; } while(res/10) { s=(ListNode*)malloc(sizeof(ListNode)); int temp=res%10; res/=10; s->val=temp; p->next=s; p=s; } if(res%10!=0) { s=(ListNode*)malloc(sizeof(ListNode)); int temp=res%10; s->val=temp; p->next=s; p=s; } head=head->next; p->next=NULL; return head; }
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45557329