當前位置:係統粉 > 電腦問答 > 其他問答 > 求一程序

求一程序

提問者:不玉則剛123  |  瀏覽 次  |  提問時間:2017-01-10  |  回答數量:1

求一程序誰有數據結構的關於單鏈表的算法的完整的程序嗎?

已有1條答案
囍你愛我225

囍你愛我225

回答數:19  |  被采納數:51

2017-01-10 15:42:37
#include<stdio.h>
#include<stdlib.h>
structpnode//鏈表的組成
{
float coef;
intexpn;
structpnode*next;
} polynode;
struct pnode *Creat(int n)//創建一鏈表
{ struct pnode *L,*p,*q;
int i;
q=L=(struct pnode *)malloc(sizeof(polynode));
L->next=NULL;
for(i=0;i<n;i++)
{p=(struct pnode *)malloc(sizeof(polynode));
scanf("%f%d",&p->coef,&p->expn);
p->next=L->next;
L->next=p;
}
return q;}
struct pnode*polyadd(struct pnode *LA,struct pnode *LB)
//實現A多項式加B多項式等於C多項式,並返回C多項式
//的表頭指針
{ struct pnode *LC,*pc,*pa,*pb;
floatx;
pa=LA->next;
pb=LB->next ;
pc=(struct pnode *)malloc(sizeof(polynode));
LC=pc;

while (pa&&pb)
{if(pa->expn==pb->expn)//同類項合並
{x=pa->coef+pb->coef;
if(x!=0)
{pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
pc->coef=x;
pc->expn=pa->expn;
}
pa=pa->next;
pb=pb->next;
}
else
{ pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
if (pa->expn<pb->expn)//a的指數小於b的指數
{ pc->coef=pa->coef;
pc->expn=pa->expn;
pa=pa->next;}
else
{ pc->coef=pb->coef;
pc->expn=pb->expn;
pb=pb->next; }
}
}
while(pa)//還乘下 a 多項式
{ pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
pc->coef=pa->coef;
pc->expn=pa->expn;
pa=pa->next;
}
while(pb)//還乘 下b 多項式
{ pc->next=(struct pnode *)malloc(sizeof(polynode));
pc=pc->next;
pc->coef=pb->coef;
pc->expn=pb->expn;
pb=pb->next;
}
pc->next=NULL;
returnLC;
}
struct pnode *print(struct pnode *L)//鏈表的打印
{
while(L->next->next)
{ L=L->next;
printf("%.2f^%d+",L->coef,L->expn);
}
L=L->next;
printf("%.2f^%d\n",L->coef,L->expn);

return L;
}
void main()
{ struct pnode *PA,*PB,*PC;
int i;
printf("請輸入多項式項數");//創建一鏈表PA
scanf("%d",&i);

PA=Creat(i);

printf("請輸入另一多項式項數");//創建一鏈表PB

scanf("%d",&i);

PB=Creat(i);

PC=polyadd( PA, PB);//得到鏈表PC

printf("多項式A=");
print(PA);

printf("多項式B=");
print(PB);

printf("運算後多項式=");
print(PC);
}
讚 1
解決方法
版權信息

Copyright @ 2011 係統粉 版權聲明 最新發布內容 網站導航