【数据结构】------一元多项式求导
要求:链表,输入数字以空格分隔,输出求导后的导数多项式,具体要求大家应该都知道,话不多说直接上代码吧(菜鸡写法,大佬勿喷)
#include <stdio.h>
#include <stdlib.h>
typedef struct Polynomial {//多项式
int coefficient;//系数
int exponential;//指数
struct Polynomial *next;
} Poly;
Poly *input() {//输入多项式
char c;
Poly *temp, *head, *p;
printf("请输入多项式:\n");
head = (Poly *)malloc(sizeof(Poly));
scanf("%d%d", &(head->coefficient), &(head->exponential));//赋值
head->next = NULL;
p = head;
while (getchar() == ' ') {//当结尾有空格时继续输入一组数,没空格时输入结束
temp = (Poly *)malloc(sizeof(Poly));
scanf("%d%d", &(temp->coefficient), &(temp->exponential));
temp->next = NULL;
p->next = temp;
p = temp;
}
return head;//返回头指针
}
Poly *derivation(Poly *head) { //求导
Poly *p;
if (head == NULL)//先判断head是否为空
return head;
while (head->coefficient == 0 || head->exponential == 0) { //head的系数,指数有一个为0,就删除该结点
p = head->next;
free(head);
head = p;
if (head == NULL)//如果删完了,就返回NULL
return head;
}
p = head;
while ( p ->next != NULL ) {//p一开始==head
if (p->next->coefficient == 0 || p->next->exponential == 0) {//删除p的下一结点中系数,指数为0的结点
Poly *delnode = p->next;
p->next = delnode->next;
free(delnode);
} else {
p = p->next;
}
}
for (p = head; p != NULL; p = p->next) { //对整理后的多项式求导
p->coefficient = p->coefficient * p->exponential;
p->exponential --;
}
return head;
}
int output(Poly *head) {//输出链表中的多项式
if (head == NULL) {//head为NULL
printf("0 0\n");
return 0;
}
Poly *p;
for (p = head; p ->next != NULL; p = p->next) {//head不为NULL时输出head中的值
printf("%d %d ", p->coefficient, p->exponential);
}
printf("%d %d\n", p->coefficient, p->exponential);//输出结尾不能有空格
return 0;
}
int main() {
Poly *head, *p;
head = input();//输入
head = derivation(head);//求导
output(head);//输出
return 0;
}