#include<stdio.h> struct ListNode { int val; struct ListNode *next; }; struct ListNode*creat()//建立新链表 { struct ListNode*head,*p; head=(struct ListNode*)malloc(sizeof(struct ListNode)); head->next=NULL; int x; scanf("%d",&x); while(x!=0)//当输入0时退出循环 { p=(struct ListNode*)malloc(sizeof(struct ListNode)); p->val=x; p->next=head->next;//头插法 head->next=p; scanf("%d",&x); } return head;//返回链表 }; void print(struct ListNode *head)//输出链表 { struct ListNode *p; p=head->next; while(p!=NULL) { printf("%d ",p->val); p=p->next; } printf("\n"); } struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) //两数相加函数 { struct ListNode *head,*r,*p,*p1,*p2; head=(struct ListNode*)malloc(sizeof(struct ListNode));//建立新链表 head->next=NULL; r=head; p1=l1->next; p2=l2->next; int c=0,item=0;//c表示每一位的数,item表示进位数 while(p1!=NULL||p2!=NULL) { p=(struct ListNode*)malloc(sizeof(struct ListNode)); p->next=NULL; r->next=p;//尾插 r=p; c=p1->val+p2->val+item; r->val=c%10; item=c/10;//进位数 p1=p1->next; p2=p2->next; } while(p1) { p=(struct ListNode*)malloc(sizeof(struct ListNode)); p->next=NULL; r->next=p; r=p; c=p1->val+item; r->val=c%10; item=c/10; p1=p1->next; } while(p2) { p=(struct ListNode*)malloc(sizeof(struct ListNode)); p->next=NULL; r->next=p; r=p; c=p2->val+item; r->val=c%10; item=c/10; p2=p2->next; } if(item!=0)//当最后一位进位数!=0时,申请新节点,并插入 { p=(struct ListNode*)malloc(sizeof(struct ListNode)); p->next=NULL; r->next=p; r=p; r->val=item; } return head; } int main() { struct ListNode *l1,*l2,*l3; l1=creat(); l2=creat(); print(l1); print(l2); l3=addTwoNumbers(l1,l2); print(l3); return 0; }
两数相加(有进位)
最新推荐文章于 2021-01-23 09:05:11 发布