LeetCode——Add Two Numbers
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:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * NodeList *next; 6 * NodeList(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *head1, ListNode *head2) { 12 int n1=0,n2=0; 13 ListNode *ptr1=head1,*ptr2=head2; 14 while(ptr1!=NULL) 15 { 16 n1++; 17 ptr1=ptr1->next; 18 } 19 while(ptr2!=NULL) 20 { 21 n2++; 22 ptr2=ptr2->next; 23 } 24 vector<int> sum; 25 int temp; 26 ListNode *head_long,*head_short; 27 if(n1>=n2) 28 { 29 head_long=head1; 30 head_short=head2; 31 } 32 else 33 { 34 head_long=head2; 35 head_short=head1; 36 } 37 ///// 38 ListNode *pt1=head_long,*pt2=head_short; 39 while(pt2!=NULL) 40 { 41 temp=pt1->val+pt2->val; 42 if(temp>=10) 43 { 44 sum.push_back(temp%10); 45 if(pt1->next==NULL) 46 { 47 sum.push_back(1); 48 } 49 else 50 pt1->next->val+=1; 51 } 52 else 53 sum.push_back(temp); 54 pt1=pt1->next;pt2=pt2->next; 55 } 56 while(pt1!=NULL) 57 { 58 temp=pt1->val; 59 if(temp>=10) 60 { 61 sum.push_back(temp%10); 62 if(pt1->next==NULL) 63 { 64 sum.push_back(1); 65 } 66 else 67 pt1->next->val+=1; 68 } 69 else 70 sum.push_back(temp); 71 pt1=pt1->next; 72 } 73 ListNode *result=new ListNode(0); 74 ListNode *rp=new ListNode(0); 75 rp=result; 76 ListNode *rq; 77 78 for(vector<int>::iterator iter=sum.begin();iter!=sum.end();iter++) 79 { 80 rq=new ListNode(0); 81 rq->val=*iter; 82 rp->next=rq; 83 rp=rq; 84 } 85 86 rp->next=NULL; 87 result=result->next; 88 return result; 89 } 90 };