第一步:创建符合要求的结构体(链表节点)
第二步:写一个可以创建链表的函数
第三步:用creatNode函数建立两个链表并初始化用来存放多项式
第四步:写一个测试函数用来测试多项式相加
第一个多项式:3x^4 + 9x^3 + x +4.
第二个多项式:4x^5 - 4x^3 + 2*x + 9.
#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
int coef; //coefficient
int expon; //指数
struct list *next; //链
}LISTN;
LISTN *createNode(int coef, int expon);
LISTN *addPolynomial(LISTN *p1, LISTN *p2);
void test(void);
int main(void)
{
test();
return 0;
}
LISTN *createNode(int coef, int expon)
{
LISTN *node = (LISTN *)malloc(sizeof(LISTN)); //建立节点
node->coef = coef;
node->expon = expon;
node->next = NULL;
return node;
}
LISTN *addPolynomial(LISTN *p1, LISTN *p2)
{
LISTN *head = createNode(0, 0); //头结点
LISTN *current = head;
while(p1 != NULL && p2 != NULL)
{
if(p1->expon > p2->expon)
{
/*如果第一个多项式的指数大于第二个多项式
**则将第一个多项式的该节点存入新链表的下一个节点
*/
current->next = createNode(p1->coef, p1->expon);
p1 = p1->next;
}
else if(p1->expon < p2->expon)
{
/*如果第一个多项式的指数大于第二个多项式
**则将第一个多项式的该节点存入新链表的下一个节点
*/
current->next = createNode(p2->coef, p2->expon);
p2 = p2->next;
}
else
{
/*如果两个多项式的指数相同
**则将它们的系数相加
*/
int coef = p1->coef + p2->coef;
if(coef != 0)
{
current->next = createNode(coef, p1->expon);
}
p1 = p1->next;
p2 = p2->next;
}
current = current->next;
}
//这里是防止两个多项式项数不相等,而导致漏项
while(p1 != NULL)
{
current->next = createNode(p1->coef, p1->expon);
p1 = p1->next;
current = current->next;
}
while(p2 != NULL)
{
current->next = createNode(p2->coef, p2->expon);
p2 = p2->next;
current = current->next;
}
return head->next;
}
/*
**数据测试 test()
*/
void test(void)
{
//创建多项式p1(3x^4+9x^3+x+4)
LISTN *p1 = createNode(3, 4);
p1->next = createNode(9, 3);
p1->next->next = createNode(1, 1);
p1->next->next->next = createNode(4, 0);
LISTN *t1 = p1;
printf("第一个多项式:");
while(t1 != NULL)
{
printf("%dx^%d ", t1->coef, t1->expon);
if (t1->next != NULL)
{
printf("+ ");
}
t1 = t1->next;
}
printf(".\n");
//创建多项式p2(4x^5-4x^3+2x+9)
LISTN *p2 = createNode(4, 5);
p2->next = createNode(-4, 3);
p2->next->next = createNode(2, 1);
p2->next->next->next = createNode(9, 0);
LISTN *t2 = p2;
printf("第二个多项式:");
while (t2 != NULL) {
printf("%dx^%d ", t2->coef, t2->expon);
if (t2->next != NULL) {
printf("+ ");
}
t2 = t2->next;
}
printf(".\n");
//相加
LISTN *result = addPolynomial(p1, p2);
printf("相加结果:");
//输出结果
while(result != NULL)
{
if(result->expon==0)
{
//若指数为0,则不用输出。
printf("%d", result->coef);
}
else
{
printf("%dx^%d ", result->coef, result->expon);
}
if(result->next != NULL)
{
printf("+ ");
}
result = result->next;
}
printf(" .\n");
}
运行结果: