数据结构三元三次多项式的存储和加法c语言源代码
时间: 2023-05-29 09:06:13 浏览: 162
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
float coef; // 系数
int expo1; // x的三次方指数
int expo2; // x的二次方指数
int expo3; // x的一次方指数
struct node *next;
} Node;
Node *create_node(float coef, int expo1, int expo2, int expo3);
Node *create_poly();
void print_poly(Node *head);
Node *add_poly(Node *head1, Node *head2);
int main() {
Node *head1 = create_poly();
Node *head2 = create_poly();
Node *head3 = add_poly(head1, head2);
printf("第一个多项式:\n");
print_poly(head1);
printf("第二个多项式:\n");
print_poly(head2);
printf("两个多项式相加的结果:\n");
print_poly(head3);
return 0;
}
Node *create_node(float coef, int expo1, int expo2, int expo3) {
Node *p = (Node *)malloc(sizeof(Node));
p->coef = coef;
p->expo1 = expo1;
p->expo2 = expo2;
p->expo3 = expo3;
p->next = NULL;
return p;
}
Node *create_poly() {
Node *head = create_node(0, 0, 0, 0); // 头结点,系数为0,指数为0
Node *tail = head;
int n; // 多项式项数
printf("请输入多项式项数:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
float coef;
int expo1, expo2, expo3;
printf("请输入第%d项的系数和指数(从高到低):", i + 1);
scanf("%f%d%d%d", &coef, &expo1, &expo2, &expo3);
Node *p = create_node(coef, expo1, expo2, expo3);
tail->next = p;
tail = p;
}
return head;
}
void print_poly(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%.2f*x^3^%d*x^2^%d*x^%d + ", p->coef, p->expo1, p->expo2, p->expo3);
p = p->next;
}
printf("0\n");
}
Node *add_poly(Node *head1, Node *head2) {
Node *head3 = create_node(0, 0, 0, 0); // 头结点,系数为0,指数为0
Node *tail = head3;
Node *p = head1->next;
Node *q = head2->next;
while (p != NULL && q != NULL) {
if (p->expo1 > q->expo1 || (p->expo1 == q->expo1 && p->expo2 > q->expo2)
|| (p->expo1 == q->expo1 && p->expo2 == q->expo2 && p->expo3 > q->expo3)) {
Node *r = create_node(p->coef, p->expo1, p->expo2, p->expo3);
tail->next = r;
tail = r;
p = p->next;
} else if (p->expo1 < q->expo1 || (p->expo1 == q->expo1 && p->expo2 < q->expo2)
|| (p->expo1 == q->expo1 && p->expo2 == q->expo2 && p->expo3 < q->expo3)) {
Node *r = create_node(q->coef, q->expo1, q->expo2, q->expo3);
tail->next = r;
tail = r;
q = q->next;
} else {
float coef = p->coef + q->coef;
if (coef != 0) {
Node *r = create_node(coef, p->expo1, p->expo2, p->expo3);
tail->next = r;
tail = r;
}
p = p->next;
q = q->next;
}
}
while (p != NULL) {
Node *r = create_node(p->coef, p->expo1, p->expo2, p->expo3);
tail->next = r;
tail = r;
p = p->next;
}
while (q != NULL) {
Node *r = create_node(q->coef, q->expo1, q->expo2, q->expo3);
tail->next = r;
tail = r;
q = q->next;
}
return head3;
}
阅读全文