// 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
*/
链表:多项式加和
最新推荐文章于 2022-03-25 12:30:07 发布