链表实现多项式及相关操作

多项式数据结构:

1
2
3
4
5
6
typedef struct polyNode *polyNodePtr;
struct polyNode {
int coef; // 整型系数部分
int expon; // 指数部分
poluNodePtr next;
};

多项式加法操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
polyNodePtr polyAdd(polyNodePtr a, polyNodePtr b)
{
polyNodePtr c, tail, zeroNode;
tail = malloc(sizeof(tail));
c = tail;

while (a && b)
{
if (a->expon == b->expon)
{
sum = a->coef + b->coef;
if (sum)
attach(sum, a->expon, &tail);

a = a->next;
b = b->next;
}
else if (a->expon > b->expon)
{
attach(a->coef, a->expon, &tail);

a = a->next;
}
else
{
attach(b->coef, b->expon, &tail);

b = b->next;
}
}

for (; a; a = a->next) attach(a->coef, a->expon, &tail);
for (; b; b = b->next) attach(b->coef, b->expon, &tail);

tail->next = NULL;

zeroNode = c;
c = c->next;
free(zeroNode);

return c;
}

多项式销毁:

1
2
3
4
5
6
7
8
9
10
void erase(polyNodePtr *p)
{
polyNodePtr node;
while (*p)
{
node = *p;
*p = (*p)->next;
free(node);
}
}

代码:poly_list.c