用链表实现两个数相加

说明:使用链表实现两个数的和,数的高位存储在链表的头部,最后输出结果。注:使用了翻转链表的功能。
#include
#include

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;
	}
	if(tmp)
	{
		Node *q=(Node*)malloc(sizeof(Node));
		q->value=1;
		p->next=q;
		p=q;
		p->next=NULL;
	}
	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;ivalue=num;
			p1->next=tmp;
			p1=tmp;
			p1->next=NULL;
		}
		for(i=0;ivalue=num;
			p2->next=tmp;
			p2=tmp;
			p2->next=NULL;
		}
		Node *p=listAdd(headm->next,headn->next);
		while(p)
		{
			printf("%d ",p->value);
			p=p->next;
		}
		printf("\n");
    }
    return 0;
}

你可能感兴趣的:(经典面试题)