下面直接是代码,话不多说:
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
int coefficiet;//系数
int index;//指数
struct _node* next;
}Node,*pNode;
pNode creat_link(void);//创建单链表并初始化
void output(pNode head);//输出链表的结果
pNode assign(pNode la, pNode lb);//系数多项式加法的实现
void destroy(pNode head);//销毁动态申请的空间
int main()
{
pNode la, lb,lc;
la = creat_link();
output(la);
printf("\n");
lb = creat_link();
output(lb);
printf("\n");
lc = assign(la, lb);
output(lc);
destroy(lc);
return 0;
}
pNode creat_link(void)
{
pNode head, p, s;
head = p = (pNode)malloc(sizeof(Node));
if (head == NULL)
return 0;
p->next = NULL;
int coefficient, index;
printf("请输入:coefficient--index(输入0代表结束)\n");
scanf("%d%d", &coefficient,&index);
/*g(x)=3x+5x*x-8x*x*x+8x~2000-6x~10000
f(x)=2+2x-4x*x+9x~4-8x~2000+12x~7500
*/
while (coefficient != 0)
{
s = (pNode)malloc(sizeof(Node));
if (s != NULL)
{
s->coefficiet = coefficient;
s->index = index;
s->next = p->next;
p->next = s;
p = s;
scanf("%d%d", &coefficient, &index);
}
else
return 0;
}
return head;
}
void destroy(pNode head)
{
pNode p, q = head;
while (q != NULL)
{
p = q;
q = q->next;
free(p);
}
}
pNode assign(pNode la, pNode lb)
{
pNode pa = la->next;
pNode pb = lb->next;
pNode lc,temp=NULL;
pNode pc = lc = la;
while (pa != NULL && pb != NULL)
{
if (pa->index <= pb->index)
{
if (pa->index == pb->index)
{
pa->coefficiet += pb->coefficiet;
pc->next = pa;
pc = pa;
pa = pa->next;
temp = pb;//中间变量将已经进行过加法的销毁
pb = pb->next;
free(temp);
}
else
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
free(lb);
return lc;
}
void output(pNode head)
{
pNode p = head->next;
while (p != NULL)
{
printf(" %dx~%d ", p->coefficiet, p->index);
p = p->next;
}
}
可以根据这两张图来帮助理解:
代码结果:
在这里试验是对的,也不知道还有什么bug。