多項式的表示
多項式的關鍵數據:
- 多項式項數
- 各項系數ai及指數i
順序存儲結構表示非零項
鏈式存儲結構表示非零項
多項式的運算
加法(減法)
Compare函數,比較P1和P2的指數大小,P1大返回1,P2大返回-1,相等返回0
Attach函數:將計算結果復制到結果多項式
乘法
法1
法2
程序構造
程序框架
讀入多項式
N為多項式的項數
輸出
完整代碼 (加法 乘法)
#include <malloc.h>
typedef struct node *pnode;
struct node{
int coef;//系數
int exp;//指數
pnode next;
};
/*將一項加入鏈表,尾插法*/
void attach(int c,int e,pnode *prear){
pnode p;
p=(pnode)malloc(sizeof(struct node));
p->coef=c;
p->exp=e;
p->next=NULL;
(*prear)->next=p;
*prear=p;
}
/*讀入多項式*/
pnode dr(){
pnode p,rear,t;
int c,e,n;
scanf("%d",&n);
p=(pnode)malloc(sizeof(struct node));
p->next=NULL;
rear=p;
while(n--){
scanf("%d%d",&c,&e);
attach(c,e,&rear);
}
t=p;p=p->next;free(t);//刪除臨時空表頭節點
return p;
}
/*相加*/
pnode add(pnode p1,pnode p2){
pnode front,rear,temp;
int sum;
rear=(pnode)malloc(sizeof(struct node));
front=rear;
while(p1&&p2){
if(p1->exp>p2->exp){
attach(p1->coef,p1->exp,&rear);
p1=p1->next;
}
else if(p1->exp<p2->exp){
attach(p2->coef,p2->exp,&rear);
p2=p2->next;
}
else{
sum=p1->coef+p2->coef;
if(sum!=0){
attach(sum,p1->exp,&rear);
}
p1=p1->next;
p2=p2->next;
}
}
for(;p1;p1=p1->next) attach(p1->coef,p1->exp,&rear);
for(;p2;p2=p2->next) attach(p2->coef,p2->exp,&rear);
rear->next=NULL;
temp=front;
front=front->next;
free(temp);//刪除臨時空表頭節點
return front;
}
/*輸出*/
void print(pnode p){
int flag=0;
if(p==NULL){
printf("0 0\n");
return;
}
while(p){
if(flag==0) flag=1;
else printf(" ");
printf("%d %d",p->coef,p->exp);
p=p->next;
}
printf("\n");
}
pnode mult(pnode p1,pnode p2){
pnode p,rear,t1,t2,t;
int c,e;
if(!p1||!p2) return NULL;
t1=p1;t2=p2;
p=(pnode)malloc(sizeof(struct node));
p->next=NULL;
rear=p;
while(t2){
attach(t1->coef*t2->coef,t1->exp+t2->exp,&rear);
t2=t2->next;
}
t1=t1->next;
while(t1){
t2=p2;rear=p;
while(t2){
e=t1->exp+t2->exp;
c=t1->coef*t2->coef;
while(rear->next&&rear->next->exp>e) rear=rear->next;
if(rear->next&&rear->next->exp==e){
if(rear->next->coef+c!=0){
rear->next->coef+=c;
}
else{
t=rear->next;
rear->next=t->next;
free(t);
}
}
else{
t=(pnode)malloc(sizeof(struct node));
t->coef=c;t->exp=e;
t->next=rear->next;
rear->next=t;
rear=rear->next;
}
t2=t2->next;
}
t1=t1->next;
}
t2=p;p=p->next;free(t2);
return p;
}
int main(){
pnode p1,p2,p3,p4;
p1=dr();
p2=dr();
p3=add(p1,p2);
p4=mult(p1,p2);
print(p4);
print(p3);
}
求導 (題目:PAT (Basic Level) Practice (中文)1010)
#include <stdio.h>
#include <malloc.h>
typedef struct node *pnode;
struct node{
int xs,zs;
pnode next;
};
pnode gz(){
int m=0,t1,t2;
char a;
pnode head=NULL,p,p1;
while(1){
scanf("%d",&t1);
scanf("%c",&a);
scanf("%d",&t2);
scanf("%c",&a);
p=(pnode)malloc(sizeof(struct node));
p->xs=t1;
p->zs=t2;
m++;
if(m==1){
head=p1=p;
}
else{
p1->next=p;
p1=p;
}
if(a=='\n') break;
}
if(head!=NULL) p->next=NULL;
return head;
}
int main(){
pnode head;
head=gz();
pnode p=head;
int flag=0;
while(p){
if(p->xs!=0&&p->zs!=0){
if(flag==0){
printf("%d %d",p->xs*p->zs,p->zs-1);
flag=1;
}
else printf(" %d %d",p->xs*p->zs,p->zs-1);
}
p=p->next;
}
if(flag==0) printf("0 0");
}