某一元多项式采用带头节点的单链表存储,编写c语言算法求其导数
时间: 2023-05-30 09:01:19 浏览: 135
数据结构(C语言)用单链表存储一元多项式-并实现两个多项式的相加运算.doc
5星 · 资源好评率100%
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef; // 系数
int exp; // 指数
struct node *next;
} PolyNode, *PolyList;
// 创建多项式
void createPoly(PolyList *L)
{
int coef, exp, flag;
PolyNode *p, *tail;
*L = (PolyNode *)malloc(sizeof(PolyNode)); // 创建头节点
(*L)->next = NULL;
tail = *L;
printf("请输入多项式的系数和指数(系数为0时停止输入):\n");
do {
flag = scanf("%d %d", &coef, &exp);
if (flag && coef != 0) {
p = (PolyNode *)malloc(sizeof(PolyNode));
p->coef = coef;
p->exp = exp;
tail->next = p;
tail = p;
}
} while (flag && coef != 0);
tail->next = NULL;
}
// 输出多项式
void printPoly(PolyList L)
{
PolyNode *p = L->next;
while (p) {
if (p->coef > 0 && p != L->next) printf("+");
if (p->coef != 1 || p->exp == 0) printf("%d", p->coef);
if (p->exp > 0) printf("x");
if (p->exp > 1) printf("^%d", p->exp);
p = p->next;
}
printf("\n");
}
// 求导数
void derivative(PolyList L)
{
PolyNode *p = L->next, *pre = L;
while (p) {
if (p->exp == 0) { // 如果指数为0,将该节点删除
pre->next = p->next;
free(p);
p = pre->next;
} else {
p->coef *= p->exp; // 求导数
p->exp--;
pre = p;
p = p->next;
}
}
}
int main()
{
PolyList L;
createPoly(&L);
printf("多项式:");
printPoly(L);
derivative(L);
printf("导数:");
printPoly(L);
return 0;
}
```
阅读全文