链表:多项式加和

// PolyList.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

struct Item
{
	Item(int num,int power)
	{
		this->num=num;
		this->power=power;
		pNext=NULL;
	}
	int num;
	int power;
	Item* pNext;
};

void printAllItems(Item* pItems)
{
	while(pItems!=NULL)
	{
		printf("(%d,%d),",pItems->num,pItems->power);
		pItems=pItems->pNext;
	}
	printf("\n");
}

Item*  AddItems(Item* pA,Item* pB)
{
	Item* pC=NULL;
	if(pA->power<pB->power)
	{
		pC=pA;
		pA=pA->pNext;
	}
	else if(pA->power==pB->power)
	{
		pC=pA;
		pC->num+=pB->num;
		pA=pA->pNext;
		pB=pB->pNext;
	}
	else if(pA->power>pB->power)
	{
		pC=pB;
		pB=pB->pNext;
	}
	Item* pC0=pC;//to return;

	while(pA!=NULL && pB!=NULL)
	{
		if(pA->power<pB->power)
		{
			pC->pNext=pA;
			pA=pA->pNext;
		}
		else if(pA->power==pB->power)
		{
			pC->pNext=pA;
			pA->num+=pB->num;
			pA=pA->pNext;
			pB=pB->pNext;
		}
		else if(pA->power>pB->power)
		{
			pC->pNext=pB;
			pB=pB->pNext;
		}
		pC=pC->pNext;
	}//while(pA && pB)
	if(pA)
	{
		pC->pNext=pA;
	}
	else
	{
		pC->pNext=pB;
	}//if(pA)
	return pC0;

}
Item*  RemoveItem(Item* pPrevItem)
{
	Item* pToRemove=pPrevItem->pNext;
	pPrevItem->pNext=pToRemove->pNext;
	return pToRemove;
}
Item*  RemoveZeroItems(Item* pItem)
{
	Item* pItem0=NULL;//to return;
	while(pItem->num==0 && pItem)
	{
	pItem=pItem->pNext;
	}//	while(pItem->num==0 && pItem)
	if(pItem)
	{
		pItem0=pItem;
	}
	else
	{
		return NULL;
	}//if(pItem)
	while(pItem->pNext)
	{
		if(pItem->pNext->num==0)
			RemoveItem(pItem);
		else
			pItem=pItem->pNext;
	}//while(pItem->pNext)
	return pItem0;
	
}

int main(int argc, char* argv[])
{
	Item  LA0(7,0),LA1(3,1),LA8(9,8),LA17(5,17); 
	Item  *pA=&LA0;
	LA0.pNext=&LA1;LA1.pNext=&LA8;LA8.pNext=&LA17;
	printAllItems(pA);
	Item  LB1(8,1),LB7(22,7),LB8(-9,8); 
	Item  *pB=&LB1;
	LB1.pNext=&LB7;LB7.pNext=&LB8;
	printAllItems(pB);
	printf("AddItems(pA,pB)===============\n");
	printAllItems(pA);
	printAllItems(pB);
	Item* pAdd=AddItems(pA,pB);
	printAllItems(pAdd);
	printf("pAddRemoveZero==================\n");
	Item*  pAddRemoveZero=RemoveZeroItems(pAdd);
	printAllItems(pAddRemoveZero);

	printf("Hello World!\n");
	return 0;
}

/*
(7,0),(3,1),(9,8),(5,17),
(8,1),(22,7),(-9,8),
AddItems(pA,pB)===============
(7,0),(3,1),(9,8),(5,17),
(8,1),(22,7),(-9,8),
(7,0),(11,1),(22,7),(0,8),(5,17),
pAddRemoveZero==================
(7,0),(11,1),(22,7),(5,17),
Hello World!
Press any key to continue
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值