C语言实现一元多项式的表示和实现
时间: 2024-02-05 08:12:52 浏览: 65
一元多项式可以用如下结构体表示:
```c
typedef struct node {
float coef; // 系数
int expo; // 指数
struct node *next; // 下一个节点的指针
} node;
```
其中,`coef` 表示系数,`expo` 表示指数,`next` 表示下一个节点的指针。
下面是一元多项式的基本操作函数实现:
1. 创建一个新的节点:
```c
node *create_node(float coef, int expo) {
node *new_node = (node *)malloc(sizeof(node));
if (new_node == NULL) {
printf("Memory allocation failed.");
exit(1);
}
new_node->coef = coef;
new_node->expo = expo;
new_node->next = NULL;
return new_node;
}
```
2. 插入一个节点到多项式中:
```c
void insert_node(node **head, float coef, int expo) {
node *new_node = create_node(coef, expo);
if (*head == NULL) {
*head = new_node;
} else {
node *cur = *head;
while (cur->next != NULL && cur->next->expo > expo) {
cur = cur->next;
}
if (cur->expo == expo) {
cur->coef += coef;
free(new_node);
} else if (cur->next == NULL) {
cur->next = new_node;
} else {
new_node->next = cur->next;
cur->next = new_node;
}
}
}
```
3. 删除一个节点:
```c
void delete_node(node **head, int expo) {
if (*head == NULL) {
printf("The polynomial is empty.\n");
return;
}
node *cur = *head;
node *pre = NULL;
while (cur != NULL && cur->expo != expo) {
pre = cur;
cur = cur->next;
}
if (cur == NULL) {
printf("The node with exponent %d does not exist.\n", expo);
return;
}
if (pre == NULL) {
*head = cur->next;
} else {
pre->next = cur->next;
}
free(cur);
}
```
4. 两个多项式相加:
```c
node *add_poly(node *p1, node *p2) {
node *head = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->expo > p2->expo) {
insert_node(&head, p1->coef, p1->expo);
p1 = p1->next;
} else if (p1->expo < p2->expo) {
insert_node(&head, p2->coef, p2->expo);
p2 = p2->next;
} else {
insert_node(&head, p1->coef + p2->coef, p1->expo);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1 != NULL) {
insert_node(&head, p1->coef, p1->expo);
p1 = p1->next;
}
while (p2 != NULL) {
insert_node(&head, p2->coef, p2->expo);
p2 = p2->next;
}
return head;
}
```
5. 两个多项式相减:
```c
node *sub_poly(node *p1, node *p2) {
node *head = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->expo > p2->expo) {
insert_node(&head, p1->coef, p1->expo);
p1 = p1->next;
} else if (p1->expo < p2->expo) {
insert_node(&head, -p2->coef, p2->expo);
p2 = p2->next;
} else {
insert_node(&head, p1->coef - p2->coef, p1->expo);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1 != NULL) {
insert_node(&head, p1->coef, p1->expo);
p1 = p1->next;
}
while (p2 != NULL) {
insert_node(&head, -p2->coef, p2->expo);
p2 = p2->next;
}
return head;
}
```
6. 两个多项式相乘:
```c
node *mul_poly(node *p1, node *p2) {
node *head = NULL;
while (p1 != NULL) {
node *p = p2;
while (p != NULL) {
insert_node(&head, p1->coef * p->coef, p1->expo + p->expo);
p = p->next;
}
p1 = p1->next;
}
return head;
}
```
以上是一元多项式的基本操作函数实现,可以根据需要进行调用。
阅读全文