c语言数据结构实现一元多项式的加法运算,以(0,0)作为输入结束
时间: 2023-05-30 09:05:48 浏览: 84
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef; // 系数
int exp; // 指数
struct node* next; // 指向下一个节点的指针
} Node;
Node* create_node(int coef, int exp) {
Node* p = (Node*)malloc(sizeof(Node));
p->coef = coef;
p->exp = exp;
p->next = NULL;
return p;
}
Node* create_poly() {
Node* head = create_node(0, 0); // 创建一个头节点
Node* tail = head; // 尾指针指向头节点
int coef, exp;
printf("请输入一元多项式的系数和指数(以0,0结束):\n");
scanf("%d,%d", &coef, &exp);
while (coef != 0 || exp != 0) { // 以(0,0)作为输入结束
Node* p = create_node(coef, exp);
tail->next = p; // 尾节点指向新节点
tail = p; // 尾指针指向新节点
scanf("%d,%d", &coef, &exp);
}
return head;
}
void print_poly(Node* head) {
Node* p = head->next;
while (p) { // 遍历链表
if (p->coef > 0 && p != head->next) { // 系数为正数需要输出“+”
printf("+");
}
printf("%d", p->coef); // 输出系数
if (p->exp > 1) { // 指数大于1需要输出“x^exp”
printf("x^%d", p->exp);
} else if (p->exp == 1) { // 指数为1只需要输出“x”
printf("x");
}
p = p->next;
}
printf("\n");
}
Node* add_poly(Node* poly1, Node* poly2) {
Node* head1 = poly1->next;
Node* head2 = poly2->next;
Node* head = create_node(0, 0); // 创建一个头节点
Node* tail = head; // 尾指针指向头节点
while (head1 && head2) { // 遍历两个链表
if (head1->exp > head2->exp) { // 如果poly1的指数大于poly2的指数
tail->next = create_node(head1->coef, head1->exp); // 将poly1的节点添加到结果链表中
head1 = head1->next;
} else if (head1->exp < head2->exp) { // 如果poly1的指数小于poly2的指数
tail->next = create_node(head2->coef, head2->exp); // 将poly2的节点添加到结果链表中
head2 = head2->next;
} else { // 如果poly1的指数等于poly2的指数
int coef = head1->coef + head2->coef;
if (coef != 0) { // 系数不为0才添加节点
tail->next = create_node(coef, head1->exp); // 将系数相加后的节点添加到结果链表中
}
head1 = head1->next;
head2 = head2->next;
}
tail = tail->next; // 尾指针指向新节点
}
// 将剩余的节点添加到结果链表中
while (head1) {
tail->next = create_node(head1->coef, head1->exp);
head1 = head1->next;
tail = tail->next;
}
while (head2) {
tail->next = create_node(head2->coef, head2->exp);
head2 = head2->next;
tail = tail->next;
}
return head;
}
int main() {
printf("请输入第一个一元多项式:\n");
Node* poly1 = create_poly();
printf("请输入第二个一元多项式:\n");
Node* poly2 = create_poly();
printf("第一个多项式:");
print_poly(poly1);
printf("第二个多项式:");
print_poly(poly2);
Node* sum = add_poly(poly1, poly2);
printf("多项式相加的结果:");
print_poly(sum);
return 0;
}