多项式的表示
多项式的关键数据:
- 多项式项数
- 各项系数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
");
return;
}
while(p){
if(flag==0) flag=1;
else printf(" ");
printf("%d %d",p->coef,p->exp);
p=p->next;
}
printf("
");
}
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=='
') 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");
}