1. 程式人生 > >Never stop believing in yourself

Never stop believing in yourself

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

typedef struct polynode
{
int coef; //多項式的係數
int exp; //指數
struct polynode *next;
}node;

node *create() //用尾插法建立一元多項式的連結串列
{
node *h,*r,*s;
int c,e;
h=(node*)malloc(sizeof(node));
r=h;
printf("coef:");
scanf("%d",&c);
printf("exp: ");
scanf("%d",&e);
while(c!=0) //輸入係數為0時,多項式的輸入結束
{
s=(node*)malloc(sizeof(node));
s->coef=c;
s->exp=e;
r->next=s;
r=s;
printf("coef:");
scanf("%d",&c);
printf("exp: ");
scanf("%d",&e);
}
r->next=NULL;
return(h);
}

void print(node *p) //輸出函式,打印出一元多項式
{
while(p->next!=NULL)
{
p=p->next;
printf(" %d*x^%d",p->coef,p->exp);

}
}

void polyadd(node *ha, node *hb)//一元多項式相加函式,用於將兩個多項式相加,然後將和多項式存放在多項式ha中,並將多項式hb刪除
{
node *p,*q,*pre,*temp;
int sum;
p=ha->next;
q=hb->next;
pre=ha;
while(p!=NULL&&q!=NULL)
{
if(p->exp<q->exp)
{
pre->next=p;
pre=pre->next;
p=p->next;
}
else if(p->exp==q->exp)
{
sum=p->coef+q->coef;
if(sum!=0)
{
p->coef=sum;
pre->next=p;pre=pre->next;p=p->next;
temp=q;q=q->next;free(temp);
}
else //如果係數和為零,則刪除結點p與q,並將指標指向下一個結點
{
temp=p->next;free(p);p=temp;
temp=q->next;free(q);q=temp;
}
}
else
{
pre->next=q;
pre=pre->next;
q=q->next;
}
}
if(p!=NULL) //將多項式A中剩餘的結點加入到和多項式中
pre->next=p;
else
pre->next=q;
}

void multipoly(node *ha,node *hb)
{ node *p,*q,*n,*m;
p=ha->next;
n=(node*)malloc(sizeof(node));
n->next=NULL;
while(p!=NULL)
{ m=(node*)malloc(sizeof(node));
for(q=hb->next;q;q=q->next)
{ m->coef=p->coef*q->coef;
m->exp=p->exp+q->exp;
m->next=NULL;
}
p=p->next;
polyadd(n,m);
}
printf("多項式的積是:/n");
printf("/n");
}


void main()
{
node *ha,*hb;
printf("請輸入多項式ha的係數與指數:/n");
ha=create();
print(ha);
printf("/n");
printf("請輸入多項式hb的係數與指數:/n");
hb=create();
print(hb);
printf("/n");
printf("多項式的和是:/n");
polyadd(ha,hb);

print(ha);
printf("/n");

 multipoly(ha,hb);
}