链表相加

#include <iostream>
#include <vector>
#include <string>

using namespace std;

typedef struct tagSNode
{
	int value;
	tagSNode* pNext;

	tagSNode(int x) :value(x), pNext(NULL){};
}SNode;
void Print(SNode* p)
{
	while (p!=NULL)
	{
		if (p->pNext == NULL)
		{
			printf("%d", p->value);
			
		}
		else
		{	
			printf("%d->", p->value);
			
		}
		p = p->pNext;
		
	}
	printf("\n");
}
SNode* Add(SNode* pHead1, SNode* pHead2)
{
	SNode* pSum = new SNode(0);//一般用0做头,但不显示
	
	SNode* p1 = pHead1->pNext;
	SNode* p2 = pHead2->pNext;


	SNode* pCur;//用来存储当前节点值
	SNode* pPos=pSum;//用来指示当前节点位置



	int carry=0;
	int value;

	while (p1&&p2)
	{
		value = p1->value + p2->value+carry;
		carry = value / 10;
		value %= 10;
		pCur = new SNode(value);
		pPos->pNext = pCur;
		pPos = pCur;

		p1 = p1->pNext;
		p2 = p2->pNext;
	}

	SNode *p = p1 ? p1 : p2;
	while (p)
	{
		value = p->value + carry;
		carry = value / 10;
		value %= 10;
		pCur = new SNode(value);
		pPos->pNext = pCur;
		pPos = pCur;

		p = p->pNext;
	}

	if (carry!=0)
		pPos->pNext =new SNode(carry);

	return pSum;

}
int main()
{
	SNode* pHead1 = new SNode(0);
	int i;
	for (i = 0; i < 6; i++)
	{
		SNode* p = new SNode(rand() % 10);
		p->pNext = pHead1->pNext;
		pHead1->pNext = p;
	}
	SNode* pHead2 = new SNode(0);
	for (i = 0; i < 9; i++)
	{
		SNode* p = new SNode(rand() % 10);
		p->pNext = pHead2->pNext;
		pHead2->pNext = p;
	}
	Print(pHead1);
	Print(pHead2);

	SNode* pSum = Add(pHead1,pHead2);
	Print(pSum);

	
}

posted @ 2016-03-13 14:44  牧羊少年10号  阅读(107)  评论(0编辑  收藏  举报