一元多項式的應用

vener_發表於2020-10-13

1.儲存結構

typedef struct
{
	float c;//係數
	int e;//指數
}Term;
typedef struct PNode
{
	Term data;
	struct PNode *next;
}PNode,PLink;

2.插入

void Insert(PLink &L,Term x)
{
	PNode *q=L,*p=L->next,*s;
	while(q)
	{
		if(p!NULL&&x.e>q->data.e&&x.e<p->data.e)
		{
			s=(PNode*)malloc(sizeof(PNode));
			s->data=x;s->next=p;q->next=s;
			return;
		}
		else if(p!=NULL&&x.e==p->data.e)
		{
			if(p->data.c+x.c==0)
			{
				q->next=p->next;
				free(p);
				return;
			}
			else
			{
				p->data.c+=x.c;
				return;
			}
		}
		else if(p==NULL&&x.e>q->data.e)
		{
			s=(PNode*)malloc(sizeof(PNode));
			s->data=x;s->next=q->next;q->next=s;
			return;
		}
		else
		{
			q=p;
			p=p->next;
		}
	}
}

3.建立

void Create(PLink &L)
{
	Term x;
	L=(PNode *)malloc(sizeof(PNode));
	L->data.e=-1;
	L->next=NULL;
	while(1)
	{
		scanf("%f%d",&x.c,&x.e);
		if(x.c==0)
			break;
		Insert(L,x);
	}
}

4.求和

void Add(PLink La,PLink Lb,PLink &Lc)
{
	PNode *s,*pa,*pb,*pcr;
	Lc=(PNode*)malloc(sizeof(PNode));
	Lc->data.e=-1;
	Lc->next=NULL;
	pa=La->next;
	pb=Lb->next;
	pcr=Lc;
	while(pa&&pb)
	{
		if(pa->data.e<pb->data.e)
		{
			s=(PNode*)malloc(sizof(PNode));
			s->data=p->data;
			s->next=NULL;
			pcr->next=s;
			pcr=s;
			pa=pa->next;
		}
		else if(pa->data.e==pb->data.e)
		{
			if(pa->data.c+pb->data.c!=0)
			{
				s=(PNode*)malloc(sizof(PNode));
			 	s->data.c=pa->data.c+pb->data.c;
				s->data.e=pa->data.e;
				s->next=NULL;
				pcr->next=s;
				pcr=s;
			}
			pa=pa->next;
			pb=pb->next;
		}
		else
		{
			s=(PNode*)malloc(sizof(PNode));
			s->data=pb->data;
			s->next=NULL;
			pcr->next=s;
			pcr=s;
		}
	}
	while(pa)
	{
		s=(PNode*)malloc(sizof(PNode));
		s->data=pa->data;
		s->next=NULL;
		pcr->next=s;
		pcr=s;
		pa=pa->next;
	}
	while(pb)
	{
		s=(PNode*)malloc(sizof(PNode));
		s->data=pb->data;
		s->next=NULL;
		pcr->next=s;
		pcr=s;
		pb=pb->next;
	}
}

5.乘積

void Mul(PLink La,PLink Lb,PLink &Lc)
{
	PNode *pa,*pb;
	Term x;
	Lc=(PNode *)malloc(sizeof(PNode));
	Lc->data.e=-1;
	Lc->next=NULL;
	pa=La->next;
	while(pa)
	{
		pb=Lb->next;
		while(pb)
		{
			x.c=pa->data.c*pb->data.c;
			x.e=pa->data.e+pb->data.e;
			Insert(Lc,x);
			pb=pb->next;
		}
		pa=pa->next;
	}
}

 

相關文章