Add Two Numbers(链表)
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
代码:
vector<int> v1; vector<int> v2; int num1; int num2; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: void insertAtTail(ListNode* &reslist,int val) { ListNode* p=reslist; while (p->next) p=p->next; ListNode* newNode=(ListNode*)malloc(sizeof(ListNode)); newNode->val=val; newNode->next=p->next; p->next=newNode; } ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if(l1==NULL&&l2==NULL) return NULL; ListNode* reslist=NULL; int jinwei=0; while(l1!=NULL&&l2!=NULL){ if((l1->val+l2->val+jinwei)<10){ if(reslist==NULL){ reslist=(ListNode*)malloc(sizeof(ListNode)); reslist->val=l1->val+l2->val+jinwei; reslist->next=NULL; }else{ insertAtTail(reslist,l1->val+l2->val+jinwei); } jinwei=0; }else{ if(reslist==NULL){ reslist=(ListNode*)malloc(sizeof(ListNode)); reslist->val=l1->val+l2->val+jinwei-10; reslist->next=NULL; }else{ insertAtTail(reslist,l1->val+l2->val+jinwei-10); } jinwei=1; } l1=l1->next; l2=l2->next; } while(l1!=NULL){ if(l1->val+jinwei<10){ insertAtTail(reslist,l1->val+jinwei); jinwei=0; }else{ insertAtTail(reslist,l1->val+jinwei-10); jinwei=1; } l1=l1->next; } while(l2!=NULL){ if(l2->val+jinwei<10){ insertAtTail(reslist,l2->val+jinwei); jinwei=0; }else{ insertAtTail(reslist,l2->val+jinwei-10); jinwei=1; } l2=l2->next; } if(l1==NULL&&l2==NULL&&jinwei!=0){ insertAtTail(reslist,jinwei); } return reslist; } }; void CreateListHead(ListNode* &head, int n) { int j=0; head = (ListNode*)malloc(sizeof(ListNode)); head->next=NULL; head->val=v1[j++]; ListNode* p=head; for (int i=1;i<n;++i) { ListNode* newNode; newNode = (ListNode*)malloc(sizeof(ListNode)); p->next=newNode; newNode->next=NULL; newNode->val=v1[j++]; p=p->next; } } void CreateListHead2(ListNode* &head, int n) { int j=0; head = (ListNode*)malloc(sizeof(ListNode)); head->next=NULL; head->val=v2[j++]; ListNode* p=head; for (int i=1;i<n;++i) { ListNode* newNode; newNode = (ListNode*)malloc(sizeof(ListNode)); p->next=newNode; newNode->next=NULL; newNode->val=v2[j++]; p=p->next; } } int main() { freopen("C:\\Users\\Administrator\\Desktop\\a.txt","r",stdin); cin>>num1; for (int i=0;i<num1;++i) { int temp; cin>>temp; v1.push_back(temp); } cin>>num2; for (int i=0;i<num2;++i) { int temp; cin>>temp; v2.push_back(temp); } ListNode* head1=NULL; CreateListHead(head1,num1); ListNode* head2=NULL; CreateListHead2(head2,num2); Solution so; ListNode* res=so.addTwoNumbers(head1,head2); return 0; }