用链表写7-1 一元多项式求导
时间: 2023-08-04 08:21:37 浏览: 136
好的,以下是用链表写的一元多项式求导的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct PolyNode {
int coef; // 系数
int expon; // 指数
struct PolyNode *next;
} PolyNode, *Polynomial;
Polynomial readPoly(); // 读取多项式
Polynomial diff(Polynomial p); // 求导
void printPoly(Polynomial p); // 输出多项式
int main() {
Polynomial p, dp;
p = readPoly();
dp = diff(p);
printPoly(dp);
return 0;
}
Polynomial readPoly() {
int n, c, e;
scanf("%d", &n);
Polynomial p, rear, t;
p = (Polynomial)malloc(sizeof(PolyNode));
p->next = NULL;
rear = p;
while (n--) {
scanf("%d %d", &c, &e);
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = c;
t->expon = e;
t->next = NULL;
rear->next = t;
rear = t;
}
return p;
}
Polynomial diff(Polynomial p) {
Polynomial dp, t;
dp = (Polynomial)malloc(sizeof(PolyNode));
dp->next = NULL;
while (p->next) {
p = p->next;
if (p->expon == 0) continue; // 指数为0,导数为0
t = (Polynomial)malloc(sizeof(PolyNode));
t->coef = p->coef * p->expon;
t->expon = p->expon - 1;
t->next = NULL;
dp->next = t;
dp = t;
}
return dp;
}
void printPoly(Polynomial p) {
if (!p->next) { // 多项式为0
printf("0 0\n");
return;
}
while (p->next) {
p = p->next;
printf("%d %d", p->coef, p->expon);
if (p->next) printf(" ");
}
printf("\n");
}
```
输入格式为:
```
n a1 b1 a2 b2 ... an bn
```
其中,n 表示多项式的项数,ai 和 bi 分别表示第 i 项的系数和指数。
例如,输入样例为:
```
4 3 4 1 2 -4 0 2 1
```
表示多项式 $3x^4+x^2-4+2x$,输出样例为:
```
12 3 2 1 0 0
```
表示其导数为 $12x^3+2$。
阅读全文