采用链式存储结构,将两个线性链表表示的一元多项式相加减,求导并输出。
#include<stdio.h>
#include<stdlib.h>typedef struct lnode
{
int coef; //系数
int index; //指数
struct lnode *next;
}node;
node *Create() //头插法建立一元多项式
{
node *p1,*p2,*head;
int x,y,i = 1;
head = (node *)malloc(sizeof(node));
head->next = NULL;
p1 = head;
p2 = head;
for(i=1; ; i++)
{
p2 = (node *)malloc(sizeof(node));
printf("输入第%d项的系数,指数:",i);
scanf("%d%d",&x,&y);
if(x==0 && y==0) //输入0 0时表示输入完成
{
break;
}
if(x == 0)
{
continue;
}
p2->coef = x;
p2->index = y;
p2->next = p1->next;
p1->next = p2;
}
return head;
}
void Sort (node *head) //将多项式中相同指数的项合并
{
node *p,*q,*p1;
for(p = head->next;p->next!=NULL;p = p->next)
{
for(q = p;q->next!=NULL;q=q->next)
{
if(p->index == q->next->index)
{
p->coef = p->coef + q->next->coef; //相同指数的项合并
q->next->coef = 0;
q->next->index = 0;
}
}
}
p = head;
q = p;
while(q->next!=NULL)
{
p1 = q;
q = q->next;
if(q->coef==0 && q->index==0)
{
p1->next = q->next;
free(q);
q = p1;
}
}
}
int Print(node *head) //打印函数
{
node *p;
int x,y;
if(head->next == NULL)
return 0;
else
p = head->next;
while(p->next != NULL)
{
if(p->index == 0)
{
printf("%d+",p->coef);
}
else if(p->next->coef<0)
{
printf("%dx^%d",p->coef,p->index);
}
else
{
printf("%dx^%d+",p->coef,p->index);
}
p = p->next;
}
if(p->index == 0)
{
printf("%d\n",p->coef);
}
else
{
printf("%dx^%d\n",p->coef,p->index);
}
return 1;
}
void Plus(node *head1,node *head2) //多项式相加
{
node *p,*q,*p1;
p = head1;
q = head2;
for(p = head1->next;p!=NULL;p = p->next)
{
for(q = head2->next;q!=NULL;q = q->next)
{
if(p->index == q->index) // //相同指数的项合并
{
p->coef = p->coef + q->coef;
q->coef = 0;
q->index = 0;
}
}
}
for(q = head2->next;q!=NULL;q = q->next)
{
if(q->coef!=0 && q->index!=0) //将第二个多项式中与第一个多项式指数不同的项 添加入第一个多项式
{
p1 = (node *)malloc(sizeof(node));
p1->coef = q->coef;
p1->index = q->index;
p1->next = head1->next;
head1->next = p1;
}
}
Print(head1);
}
void Minus(node *head1,node *head2) // 多项式相加(同相减)
{
node *p,*q,*p1;
p = head1;
q = head2;
for(p = head1->next;p!=NULL;p = p->next)
{
for(q = head2->next;q!=NULL;q = q->next)
{
if(p->index == q->index)
{
p->coef = p->coef - q->coef;
q->coef = 0;
q->index = 0;
}
}
}
for(q = head2->next;q!=NULL;q = q->next)
{
if(q->coef!=0 && q->index!=0)
{
p1 = (node *)malloc(sizeof(node));
p1->coef = 0-q->coef;
p1->index = q->index;
p1->next = head1->next;
head1->next = p1;
}
}
Print(head1);
}
void derivative(node *head) //求多项式的导数
{
node *p;
p = head->next;
while(p!=NULL)
{
p->coef = p->coef*p->index;
p->index = p->index-1;
p = p->next;
}
printf("多项式的导数为:");
Print(head);
}
int main()
{
node *head1,*head2,*head;
int x;
printf("输入第一个多项式的系数,指数(输入0 0时结束输入):\n");
head1 = Create();
Sort(head1);
Print(head1);
printf("输入第二个多项式的系数,指数(输入0 0时结束输入):\n");
head2 = Create();
Sort(head2);
Print(head2);
printf("选择运算:");
scanf("%d",&x);
switch(x)
{
case 1:derivative(head1);break;
case 2:derivative(head2);break;
case 3:Plus(head1,head2);break;
case 4: Minus(head1,head2);break;
}
}