C语言链表完成多项式的降幂输出
时间: 2023-07-04 13:17:23 浏览: 98
C语言:一元多项式加减法运算(链表 附答案).docx
假设多项式的项的结构体如下所示:
```c
typedef struct Term {
int coef; // 系数
int expn; // 指数
struct Term *next;
} Term;
```
则可以按照以下步骤完成多项式的降幂输出:
1. 定义一个指针p指向多项式头节点。
2. 定义一个数组arr,用于存储多项式的每一项。
3. 遍历多项式,将每一项依次存入数组arr中。
4. 对数组arr进行降序排序。
5. 遍历数组arr,将每个元素输出。
下面是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Term {
int coef; // 系数
int expn; // 指数
struct Term *next;
} Term;
void insert(Term **head, int coef, int expn) {
Term *new_node = (Term*)malloc(sizeof(Term));
new_node->coef = coef;
new_node->expn = expn;
new_node->next = *head;
*head = new_node;
}
void print_poly(Term *head) {
Term *p = head;
while (p != NULL) {
if (p->coef > 0) {
printf("+");
}
printf("%dx^%d", p->coef, p->expn);
p = p->next;
}
}
void print_poly_desc(Term *head) {
Term *p = head;
int count = 0;
while (p != NULL) {
count++;
p = p->next;
}
Term *arr[count];
p = head;
int i = 0;
while (p != NULL) {
arr[i] = p;
p = p->next;
i++;
}
for (int j = 0; j < count; j++) {
for (int k = j + 1; k < count; k++) {
if (arr[j]->expn < arr[k]->expn) {
Term *temp = arr[j];
arr[j] = arr[k];
arr[k] = temp;
}
}
if (arr[j]->coef > 0) {
printf("+");
}
printf("%dx^%d", arr[j]->coef, arr[j]->expn);
}
}
int main() {
Term *poly = NULL;
insert(&poly, 3, 2);
insert(&poly, 4, 3);
insert(&poly, 5, 1);
insert(&poly, 2, 4);
printf("原始多项式:");
print_poly(poly);
printf("\n降幂输出:");
print_poly_desc(poly);
printf("\n");
return 0;
}
```
输出结果为:
```
原始多项式:+2x^4+5x^1+4x^3+3x^2
降幂输出:+2x^4+4x^3+3x^2+5x^1
```
阅读全文