#include <stdio.h>
#include <stdlib.h>
struct node {
int coef; //系数
int index; //指数
struct node *next;
};
//初始化linklist
struct node *init_ll() {
struct node *p;
p = (struct node *)malloc(sizeof(struct node)); //为节点指针分配内存空间
p->next = NULL; //*为节点的next值赋值为NULL方便表的遍历,作为遍历为结尾的判断条件
return p; //返回指针,便于操作
}
//头插法插入linklist
void insert_ll(struct node *head, int coef, int index) {
struct node *p;
p = (struct node *)malloc(sizeof(struct node)); //为节点指针分配内存空间
p->coef = coef; //实例化系数
p->index = index; //实例化指数
p->next = head->next; //*该节点的next指针指向head指向的节点
head->next = p; //*插入在头指针的后面
}
//打印输出linklist
void reverse_ll(struct node *head) {
struct node *p;
p = head->next;
while (p != NULL) { //为空时结束循环
printf("%d次项系数为%d ", p->index, p->coef); //打印输出
p = p->next; //指针迭代,进行循环输出
}
printf("\n");
}
//销毁linklist释放空间
void destory_ll(struct node *head) {
struct node *p, *q;
p = head->next;
while (p != NULL) {
q = p;
p = p->next;
free(q);
}
free(head);
}
//两个多项式进行相加操作
void add_poly(struct node *head1, int length1, struct node *head2, int length2) {
struct node *p1;
struct node *p2;
if (length1 > length2) {
p1 = head1->next;
p2 = head2->next;
while (p1 != NULL) {
if (p1->index == p2->index) {
p1->coef = (p1->coef) + (p2->coef);
p2 = p2->next;
}
p1 = p1->next;
}
}
else {
p1 = head1->next;
p2 = head2->next;
while (p2 != NULL) {
if (p1->index == p2->index) {
p2->coef = (p2->coef) + (p1->coef);
p1 = p1->next;
}
p2 = p2->next;
}
}
}
//两个多项式进行相减操作
void sub_poly(struct node *head1, int length1, struct node *head2, int length2) {
struct node *p1;
struct node *p2;
if (length1 > length2) {
p1 = head1->next;
p2 = head2->next;
while (p1 != NULL) {
if (p1->index == p2->index) {
p1->coef = (p1->coef) - (p2->coef);
p2 = p2->next;
}
p1 = p1->next;
}
}
else {
p1 = head1->next;
p2 = head2->next;
while (p2 != NULL) {
p2->coef = -(p2->coef);
if (p1->index == p2->index) {
p2->coef = (p2->coef) + (p1->coef);
p1 = p1->next;
}
p2 = p2->next;
}
}
}
main(void) {
struct node *head1; //多项式1 头节点
struct node *head2; //多项式2 头节点
int index_current = 0; //要输入的指数
int coef_current = 0; //要输入的系数
int index_max1; //多项式1 次数
int index_max2; //多项式2 次数
int i = 0; //循环控制变量
head1 = init_ll();
printf("-请输入第一个多项式的次数-\n");
scanf_s("%d",&index_max1);
for (i = 0; i < index_max1; i++) {
printf("-请输入%d次项系数:", index_current);
scanf_s("%d", &coef_current);
insert_ll(head1, coef_current,index_current); //头插法
index_current++;
}
head2 = init_ll();
index_current = 0;
printf("-请输入第二个多项式的次数-\n");
scanf_s("%d", &index_max2);
for (i = 0; i < index_max2; i++) {
printf("-请输入%d次项系数:", index_current);
scanf_s("%d", &coef_current);
insert_ll(head2, coef_current, index_current); //头插法
index_current++;
}
add_poly(head1, index_max1, head2, index_max2); //进行相加操作
//sub_poly(head1, index_max1, head2, index_max2); //进行相减操作
printf("多项式1的结果为:");
reverse_ll(head1);
printf("多项式2的结果为:");
reverse_ll(head2);
destory_ll(head1);
destory_ll(head2);
getchar();
getchar();
}
C语言实现多项式的相加(链表)
最新推荐文章于 2024-09-16 11:55:01 发布