Add Two Numbers

来源:互联网 发布:mac 桌面壁纸位置 编辑:程序博客网 时间:2024/05/24 03:03
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */ int LengthList(struct ListNode* head); struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){int lengLong=LengthList(l1);int lengshort=LengthList(l2);struct ListNode* pCurrent;int tmp;if(lengLong<lengshort){pCurrent=l1;l1=l2;l2=pCurrent;tmp=lengLong;        lengLong=lengshort;lengshort=tmp;}struct ListNode* SumNumberHead=(struct ListNode*)malloc(sizeof(struct ListNode)); int carry=0; //存储进位int i=0;int j=0;pCurrent=SumNumberHead;  //存储和的头struct ListNode* pCurrent1=l1;struct ListNode* pCurrent2=l2;struct ListNode* pCurrentForTail;for(;j<lengshort;i++,j++){//每一位相加pCurrent->val=pCurrent1->val+pCurrent2->val+carry;if(pCurrent->val/10>0){    carry=pCurrent->val/10;pCurrent->val=pCurrent->val%10;}elsecarry=0; //没有进位..pCurrent1=pCurrent1->next;pCurrent2=pCurrent2->next;struct ListNode* NewNode=(struct ListNode*)malloc(sizeof(struct ListNode)); pCurrent->next=NewNode; //让他有节点.pCurrentForTail=pCurrent;pCurrent=pCurrent->next;}//i,j可以只用一个for(;i<lengLong;i++){pCurrent->val=pCurrent1->val+carry;if(pCurrent->val/10>0){    carry=pCurrent->val/10;pCurrent->val=pCurrent->val%10;}elsecarry=0; //没有进位..pCurrent1=pCurrent1->next;struct ListNode* NewNode=(struct ListNode*)malloc(sizeof(struct ListNode)); pCurrent->next=NewNode; //让他有节点.pCurrentForTail=pCurrent;pCurrent=pCurrent->next;}if(carry>0){pCurrent->val=carry;        pCurrentForTail=pCurrent;pCurrent=pCurrent->next;}pCurrentForTail->next=NULL;//记录一个pCurrent之前的节点return SumNumberHead;}int LengthList(struct ListNode* head) {if(head==NULL)return 0;int length=0;struct ListNode* pCurrent=head;while(pCurrent!=NULL){length++;pCurrent=pCurrent->next;}//free(pCurrent);return length;}

0 0