data-structure-experiments/10/main.c

164 lines
3.8 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 1.问题描述
// 设计一个一元稀疏多项式简单计算器。
// 2.基本要求
// 一元稀疏多项式简单计算器的基本功能是:
// (1)输入并建立多项式;
// (2)输出多项式,输出形式为整数序列:
// n,c1,e1,c2,e2,…,cn,en,
// 其中n是多项式的项数ci,ei分别是第i项的系数和指数序列按指数降序排列
// (3)多项式a和b相加建立多项式a+b
// (4)多项式a和b相减建立多项式a-b
// (5)计算多项式在x处的值即给定x值计算多项式值。
// 3.实现提示
// 用带表头结点的单链表存储多项式,多项式的项数存放在头结点中。
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int c, e;
struct Node *next;
} Node;
typedef struct List {
Node head;
int len;
} List;
List *init_list() {
List *l = (List *)malloc(sizeof(List));
l->head.next = NULL;
l->len = 0;
return l;
}
// 降序插入
void insert(List *l, int c, int e) {
Node *p = &(l->head);
while (p->next && p->next->e > e) {
p = p->next;
}
if (p->next && p->next->e == e) {
p->next->c += c;
if (p->next->c == 0) {
Node *q = p->next;
p->next = q->next;
free(q);
l->len--;
}
} else {
Node *q = (Node *)malloc(sizeof(Node));
q->c = c, q->e = e;
q->next = p->next;
p->next = q;
l->len++;
}
}
// 只输出
void output(List *l) {
Node *p = l->head.next;
printf("%d,", l->len);
while (p) {
printf("%d,%d", p->c, p->e);
p = p->next;
if (p)
printf(",");
}
printf("\n");
}
// 只输出
void plus(List *l1, List *l2) {
Node *p1 = l1->head.next, *p2 = l2->head.next;
while (p1 && p2) {
if (p1->e > p2->e) {
printf("%d,%d,", p1->c, p1->e);
p1 = p1->next;
} else if (p1->e < p2->e) {
printf("%d,%d,", p2->c, p2->e);
p2 = p2->next;
} else {
printf("%d,%d,", p1->c + p2->c, p1->e);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1) {
printf("%d,%d,", p1->c, p1->e);
p1 = p1->next;
}
while (p2) {
printf("%d,%d,", p2->c, p2->e);
p2 = p2->next;
}
printf("\n");
}
// 只输出
void minus(List *l1, List *l2) {
Node *p1 = l1->head.next, *p2 = l2->head.next;
while (p1 && p2) {
if (p1->e > p2->e) {
printf("%d,%d,", p1->c, p1->e);
p1 = p1->next;
} else if (p1->e < p2->e) {
printf("%d,%d,", -p2->c, p2->e);
p2 = p2->next;
} else {
printf("%d,%d,", p1->c - p2->c, p1->e);
p1 = p1->next;
p2 = p2->next;
}
}
while (p1) {
printf("%d,%d,", p1->c, p1->e);
p1 = p1->next;
}
while (p2) {
printf("%d,%d,", -p2->c, p2->e);
p2 = p2->next;
}
printf("\n");
}
int calc(List *l, int x) {
int sum = 0;
Node *p = l->head.next;
while (p) {
sum += p->c * pow(x, p->e);
p = p->next;
}
return sum;
}
int main() {
// freopen("data.in", "r", stdin);
List *l = init_list();
List *l2 = init_list();
int n1, n2, c, e;
scanf("%d", &n1);
for (int i = 0; i < n1; i++) {
scanf("%d%d", &c, &e);
insert(l, c, e);
}
scanf("%d", &n2);
for (int i = 0; i < n2; i++) {
scanf("%d%d", &c, &e);
insert(l2, c, e);
}
output(l);
output(l2);
plus(l, l2);
minus(l, l2);
while (1) {
printf("请输入x的值");
scanf("%d", &c);
if (c == -1)
break;
printf("%d\n", calc(l, c));
}
return 0;
}