标签:
Question:
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
Solution:
/** * Definition for singly-linked list. * struct ListNode { * int val; * NodeList *next; * NodeList(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *addTwoNumbers(ListNode *head1, ListNode *head2) { int n1=0,n2=0; ListNode *ptr1=head1,*ptr2=head2; while(ptr1!=NULL) { n1++; ptr1=ptr1->next; } while(ptr2!=NULL) { n2++; ptr2=ptr2->next; } vector<int> sum; int temp; ListNode *head_long,*head_short; if(n1>=n2) { head_long=head1; head_short=head2; } else { head_long=head2; head_short=head1; } ///// ListNode *pt1=head_long,*pt2=head_short; while(pt2!=NULL) { temp=pt1->val+pt2->val; if(temp>=10) { sum.push_back(temp%10); if(pt1->next==NULL) { sum.push_back(1); } else pt1->next->val+=1; } else sum.push_back(temp); pt1=pt1->next;pt2=pt2->next; } while(pt1!=NULL) { temp=pt1->val; if(temp>=10) { sum.push_back(temp%10); if(pt1->next==NULL) { sum.push_back(1); } else pt1->next->val+=1; } else sum.push_back(temp); pt1=pt1->next; } ListNode *result=new ListNode(0); ListNode *rp=new ListNode(0); rp=result; ListNode *rq; for(vector<int>::iterator iter=sum.begin();iter!=sum.end();iter++) { rq=new ListNode(0); rq->val=*iter; rp->next=rq; rp=rq; } rp->next=NULL; result=result->next; return result; } };
标签:
原文地址:http://www.cnblogs.com/riden/p/4564485.html