【数据结构】------一元多项式求导

【数据结构】------一元多项式求导

要求:链表,输入数字以空格分隔,输出求导后的导数多项式,具体要求大家应该都知道,话不多说直接上代码吧(菜鸡写法,大佬勿喷)

#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;
}

  • 5
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值