数据结构作业,多项式相乘
#include <stdio.h>
#include <stdlib.h>
typedef struct Stack
{
float xishu;
int zhishu;
struct Stack *next;
}snode,*stack;
int initstack(stack &S)
{
S=(stack)malloc(sizeof(snode));
S->next=NULL;
return 1;
}
int enstack(stack &S,float i,int j)
{
stack L=S,P;
while(L->next)
L=L->next;
P=(stack)malloc(sizeof(snode));
P->next=NULL;
P->xishu=i;
P->zhishu=j;
L->next=P;
return 1;
}
void create(stack &L)
{
L=(stack)malloc(sizeof(snode));
L->next=NULL;
int j;float i;
char yn;
stack P=L,S;
do
{
printf("input the zhishi:\n");
scanf("%d",&j);
printf("input the xishu:\n");
scanf("%f",&i);getchar();
S=(stack)malloc(sizeof(snode));
S->next=NULL;
S->xishu=i;
S->zhishu=j;
P->next=S;
P=S;
printf("Continue?:\n");
yn=getchar();
}while(yn=='y');
}
void disp(stack S)
{
stack P=S->next;
while(P)
{
printf("%.1fX^%d",P->xishu,P->zhishu);
if(P->next)
printf("+");
P=P->next;
}
}
void add(stack &P,stack &Q,stack &S)
{
stack p=P->next,q=Q->next,s=S;stack L;L=(stack)malloc(sizeof(snode));L->next=NULL;
float i;
int j;
while(p&&q)
{
if(p->zhishu<q->zhishu)
{
L=(stack)malloc(sizeof(snode));
L->xishu=p->xishu;
L->zhishu=p->zhishu;
L->next=NULL;
s->next=L;
s=L;
p=p->next;
}
else if(p->zhishu>q->zhishu)
{
L=(stack)malloc(sizeof(snode));
L->xishu=q->xishu;
L->zhishu=q->zhishu;
L->next=NULL;
s->next=L;
s=L;
q=q->next;
}
else if(p->zhishu==q->zhishu)
{
i=p->xishu+q->xishu;
if(i!=0)
{
L=(stack)malloc(sizeof(snode));
L->xishu=i;
L->zhishu=p->zhishu;
L->next=NULL;
s->next=L;
s=L;
p=p->next;q=q->next;
}
}
}
if(p)
s->next=p;
if(q)
s->next=q;
}//多项式相加
stack multiply(stack P,stack Q,stack &S)
{
stack p=P->next,q=Q->next;
stack L;L=(stack)malloc(sizeof(snode));L->next=NULL;
stack s=L,T;stack l;T=(stack)malloc(sizeof(snode));T->next=NULL;
while(p)
{
while(q)
{
l=(stack)malloc(sizeof(snode));
l->next=NULL;
int j;float i;
j=p->zhishu+q->zhishu;
i=p->xishu*q->xishu;
l->xishu=i;l->zhishu=j;
s->next=l;
s=l;
q=q->next;
}
q=Q->next;
p=p->next;
add(S,L,T);
S = T;
L->next=NULL;s=L;
}
return T;
}//多项式相乘
int main()
{
stack P,S,Q;
create(P);printf("\n---------------\n");
create(Q);printf("\n---------------\n");
S=(stack)malloc(sizeof(snode));
S->next=NULL;
stack T;
T=multiply(P,Q,S);
disp(T);
return 0;
}