#include<stdio.h> #include<stdlib.h> struct Node { int value; Node *next; }; Node *reverseList(Node *head) { Node *pCur=head; Node *pPre=NULL; Node *rHead=NULL; while(pCur!=NULL) { Node *pNext=pCur->next; if(pNext==NULL) rHead=pCur; pCur->next=pPre; pPre=pCur; pCur=pNext; } return rHead; } Node *listAdd(Node *headm,Node *headn) { if(headm==NULL&&headn) return headn; else if(headn==NULL&&headm) return headm; else if(headn==NULL&&headm==NULL) return NULL; Node *pm=reverseList(headm); Node *pn=reverseList(headn); Node *head=(Node*)malloc(sizeof(Node)); Node *p=head; p->next=NULL; int tmp=0; while(pm&&pn) { Node *q=(Node*)malloc(sizeof(Node)); if((pm->value+pn->value+tmp)>=10) { q->value=pm->value+pn->value-10+tmp; tmp=1; } else { q->value=pm->value+pn->value+tmp; tmp=0; } p->next=q; p=q; p->next=NULL; pm=pm->next; pn=pn->next; } while(pm) { Node *q=(Node*)malloc(sizeof(Node)); int count=pm->value+tmp; if(count>=10) { q->value=count-10; tmp=1; } else { q->value=count; tmp=0; } p->next=q; p=q; p->next=NULL; pm=pm->next; } while(pn) { Node *q=(Node*)malloc(sizeof(Node)); int count=pn->value+tmp; if(count>=10) { q->value=count-10; tmp=1; } else { q->value=count; tmp=0; } p->next=q; p=q; p->next=NULL; pn=pn->next; }
<span style="white-space:pre"> if(tmp) <span style="white-space:pre"> </span>{ <span style="white-space:pre"> </span>Node *q=(Node*)malloc(sizeof(Node)); <span style="white-space:pre"> </span>q->value=1; <span style="white-space:pre"> </span>p->next=q; <span style="white-space:pre"> </span>p=q; <span style="white-space:pre"> </span>p->next=NULL; <span style="white-space:pre"> </span>}</span> return reverseList(head->next); } int main() { int m,n,i; while(scanf("%d %d",&m,&n)!=EOF) { Node* headm=(Node*)malloc(sizeof(Node)); Node* headn=(Node*)malloc(sizeof(Node)); Node *p1=headm,*p2=headn; p1->next=NULL,p2->next=NULL; for(i=0;i<m;i++) { int num; scanf("%d",&num); Node *tmp=(Node*)malloc(sizeof(Node)); tmp->value=num; p1->next=tmp; p1=tmp; p1->next=NULL; } for(i=0;i<n;i++) { int num; scanf("%d",&num); Node *tmp=(Node*)malloc(sizeof(Node)); tmp->value=num; p2->next=tmp; p2=tmp; p2->next=NULL; } Node *p=listAdd(headm->next,headn->next); //Node *p=reverseList(headm->next); while(p) { printf("%d ",p->value); p=p->next; } printf("\n"); } return 0; }
原文:http://blog.csdn.net/zyh920521/article/details/46522477