-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolynomial.c
More file actions
62 lines (62 loc) · 1.24 KB
/
polynomial.c
File metadata and controls
62 lines (62 loc) · 1.24 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef;
int exp;
struct node *next;
} polynomial;
int add(float coef, int exp, struct node **headref)
{
struct node *p, *q;
if (!headref) return -1; /*error*/
p = *headref;
q = malloc(sizeof(struct node));
if (!q) {
perror("no memory");
return -1; /*error*/
}
q->coef = coef, q->exp = exp;
if (!p) {
*headref = q;
return 0;
}
while (p->next) p = p->next;
p->next = q;
return 0;
}
void freeall(struct node *head)
{
if (head) {
struct node *cur = head;
while (cur) {
struct node *tmp = cur;
cur = cur->next;
free(tmp);
}
head = NULL;
}
}
void printall(struct node *head)
{
if (head) {
struct node *cur = head;
while (cur) {
if (cur == head)
printf("%dx^%d", cur->coef, cur->exp);
else
printf(" + %dx^%d", cur->coef, cur->exp);
cur = cur->next;
}
printf("\n");
}
}
int main(void)
{
struct node *head = NULL;
add(3, 2, &head);
add(5, 1, &head);
add(9, 0, &head);
printall(head);
freeall(head);
return 0;
}