多项式合并

#include

#include

//多项式的节点

typedef struct PNode{

int exp;

int coef;

struct PNode *link;

}PNode;

//多项式的头结点

typedef struct polynominal{

PNode *head;

} polynominal;

//初始化多项式

void Create(polynominal *p){

PNode *pn, *pre, *q;

p->head = (PNode*)malloc(sizeof(PNode));

p->head->exp = -1;

p->head->link = NULL;

for (;;){

pn = (PNode*)malloc(sizeof(PNode));

printf("coef:\n");

scanf_s("%d", &pn->coef);

printf("exp:\n");

scanf_s("%d", &pn->exp);

if (pn->exp < 0) break;

pre = p->head;

q = p->head->link;

while (q&&q->exp>pn->exp){

pre = q;

q = q->link;

}

pn->link = q;

pre->link = pn;

}

}

//多项式加法

void Add(polynominal *px, polynominal *qx){

PNode *q, *ql = qx->head, *p, *temp;

p = px->head->link;

q = ql->link;

while (p&&q){

while (p->exp < q->exp){

ql = q;

q = q->link;

}

if (p->exp == q->exp){

q->coef = q->coef + p->coef;

if (q->coef == 0){

ql->link = q->link;

free(q);

q = ql->link;

p = p->link;

}

else{

ql = q;

q = q->link;

p = p->link;

}

}

else{

temp = (PNode*)malloc(sizeof(PNode));

temp->coef = p->coef;

temp->exp = p->exp;

temp->link = ql->link;

ql->link = temp;

p = p->link;

}

}

}

void Output(polynominal *p){//打印多项式

if (p == NULL || p->head == NULL)

return;

struct PNode *q = p->head;

while (q){

if (q->exp == -1 || q->coef == -1){

q = q->link;

continue;

}

if (q->link)

printf("%dX^%d + ", q->coef, q->exp);

else

printf("%dX^%d", q->coef, q->exp);

q = q->link;

}

printf("\n");

}

void Destroy(polynominal *p){//撤销多项式

if (p == NULL || p->head == NULL)

return;

struct PNode *pre;

while (p->head){

pre = p->head->link;

free(p->head);

p->head = pre;

}

}

int main(){

polynominal *demo1 = (polynominal*)malloc(sizeof(polynominal));

polynominal *demo2 = (polynominal*)malloc(sizeof(polynominal));

printf("P(x):\n");

Create(demo1);//初始化多项式

printf("Q(x):\n");

Create(demo2);//初始化多项式

printf("P(x) add Q(x):\n");

Output(demo1);//输出多项式

Output(demo2);//输出多项式

Add(demo1, demo2);//加法运算

printf("P(x) add Q(x) last:\n");

Output(demo2);//输出多项式

printf("P(x) and Q(x) Destroy:\n");

Destroy(demo1);//撤销多项式

Destroy(demo2);//撤销多项式

printf("P(x) and Q(x):\n");

Output(demo1);//输出多项式

Output(demo2);//输出多项式

system("pause");

return 0;

}

你可能感兴趣的:(多项式合并)