一、多项式加法
1.完整代码
#include <stdio.h>
#include <iostream>
using namespace std;
typedef struct LinkNode
{
int coefficient;
int exponent;
struct LinkNode *next;
}*LinkList,*NodePtr;
LinkList initLinkList()
{
LinkList tempHeader = new LinkNode;
tempHeader->coefficient = 0;
tempHeader->exponent = 0;
tempHeader->next = NULL;
return tempHeader;
}
bool printNode(NodePtr paraPtr,char paraChar)
{
if(!paraPtr)
return false;
printf("The element of %c is (%d * 10^%d)\n",paraChar,paraPtr->coefficient,paraPtr->exponent);
return true;
}
void appendElement(LinkList paraHeader,int paraCoefficient,int paraExponent)
{
NodePtr q=NULL,p=NULL;
q = new struct LinkNode;
q->coefficient = paraCoefficient;
q->exponent = paraExponent;
q->next = NULL;
p = paraHeader;
while(p->next)
{
p = p->next;
}
p->next = q;
}
void add(NodePtr paraList1, NodePtr paraList2)
{
NodePtr s = NULL,p = NULL,q = NULL,r = NULL;
p = paraList1->next;
q = paraList2->next;
r = paraList1;
delete paraList2;
while(p && q->next)
{
if(p->exponent < q->exponent)
{
r = p;
p = p->next;
}else if(p->exponent > q->exponent)
{
r->next = q;
r = q;
q = q->next;
}else if(p->exponent == q->exponent)
{
p->coefficient = p->coefficient + q->coefficient;
printf("The coefficient is: %d.\r\n", p->coefficient);
if(p->coefficient == 0)
{
s = p;
p = p->next;
delete s;
}else
{
r = p;
p = p->next;
}
s = q;
q = q->next;
delete s;
}
}
if(!p)
r->next = q;
else
r->next = p;
cout<<endl<<"Addition ends."<<endl;
}
void printList(LinkList paraHeader)
{
NodePtr p = paraHeader;
while(p)
{
printf("%d * 10^%d + ", p->coefficient, p->exponent);
p = p->next;
}
cout<<endl<<endl;
}
void additionTest(){
LinkList tempList1 = initLinkList();
appendElement(tempList1, 7, 0);
appendElement(tempList1, 3, 1);
appendElement(tempList1, 9, 8);
appendElement(tempList1, 5, 17);
appendElement(tempList1, 19, 27);
appendElement(tempList1, 6, 21);
printList(tempList1);
LinkList tempList2 = initLinkList();
appendElement(tempList2, 8, 1);
appendElement(tempList2, 22, 7);
appendElement(tempList2, -9, 8);
printList(tempList2);
add(tempList1, tempList2);
printList(tempList1);
}
int main(){
additionTest();
printf("Finish.\r\n");
system("pause");
return 0;
}
2.运行结果