输入多个多项表达式: 3^x^5+x+5 每一个表达式使用一个链表存储,最终实现多个多项表达式相加的结果,并输出。C语言实现
时间: 2023-05-26 07:04:37 浏览: 91
用C写的一个算24点代码,使用逆波兰表达式的求值.zip
这里给出一种参考实现方式:
首先,定义一个多项式项的结构体,包含指数和系数两个成员:
```c
typedef struct term {
int exp; // 指数
float coef; // 系数
struct term *next; // 下一项
} Term;
```
然后,定义一个多项式的结构体,包含头指针和元素个数两个成员:
```c
typedef struct polynomial {
Term *head; // 链表头指针
int size; // 元素个数
} Polynomial;
```
接下来,实现多项式的基本操作,包括创建、销毁、添加项、相加等:
```c
// 创建一个空的多项式
Polynomial* create_polynomial() {
Polynomial *P = malloc(sizeof(Polynomial));
P->head = NULL;
P->size = 0;
return P;
}
// 销毁一个多项式
void destroy_polynomial(Polynomial *P) {
Term *p = P->head;
while (p != NULL) {
Term *q = p->next;
free(p);
p = q;
}
free(P);
}
// 添加一个项到多项式中,按照指数从小到大的顺序插入
void add_term(Polynomial *P, int exp, float coef) {
Term *t = malloc(sizeof(Term));
t->exp = exp;
t->coef = coef;
t->next = NULL;
if (P->size == 0) {
// 如果多项式为空,直接插入作为头结点
P->head = t;
} else {
// 否则按照指数从小到大的顺序插入
Term *p = P->head;
while (p->next != NULL && p->next->exp < exp) {
p = p->next;
}
t->next = p->next;
p->next = t;
}
P->size++;
}
// 从字符串中解析出一个多项式,返回多项式的指针
Polynomial* parse_polynomial(char *str) {
Polynomial *P = create_polynomial();
int len = strlen(str);
int i = 0;
float coef = 0;
int exp = 0;
int neg = 0;
while (i < len) {
int c = str[i];
if (c == '-') {
neg = 1;
} else if (c == '+') {
// 添加上一项
if (coef != 0) {
if (neg) {
coef = -coef;
neg = 0;
}
add_term(P, exp, coef);
coef = 0;
exp = 0;
}
} else if (isdigit(c)) {
// 解析系数或指数
int val = c - '0';
i++;
while (i < len && isdigit(str[i])) {
val = val * 10 + str[i] - '0';
i++;
}
if (exp == 0) {
if (coef == 0) {
coef = val;
} else {
coef *= val;
}
} else {
exp *= val;
}
i--;
} else if (isalpha(c)) {
// 解析变量和指数
if (exp == 0) {
exp = 1;
}
if (coef == 0) {
coef = 1;
}
if (i+1 < len && str[i+1] == '^') {
i += 2;
int val = 0;
while (i < len && isdigit(str[i])) {
val = val * 10 + str[i] - '0';
i++;
}
exp *= val;
i--;
}
}
i++;
}
// 添加最后一项
if (coef != 0) {
if (neg) {
coef = -coef;
}
add_term(P, exp, coef);
}
return P;
}
// 多项式相加
Polynomial* add_polynomial(Polynomial *P1, Polynomial *P2) {
Polynomial *P = create_polynomial();
Term *p1 = P1->head;
Term *p2 = P2->head;
while (p1 != NULL && p2 != NULL) {
if (p1->exp < p2->exp) {
add_term(P, p1->exp, p1->coef);
p1 = p1->next;
} else if (p1->exp > p2->exp) {
add_term(P, p2->exp, p2->coef);
p2 = p2->next;
} else {
float coef = p1->coef + p2->coef;
if (coef != 0) {
add_term(P, p1->exp, coef);
}
p1 = p1->next;
p2 = p2->next;
}
}
while (p1 != NULL) {
add_term(P, p1->exp, p1->coef);
p1 = p1->next;
}
while (p2 != NULL) {
add_term(P, p2->exp, p2->coef);
p2 = p2->next;
}
return P;
}
```
最后,根据输入的多项式字符串,解析出多项式,相加并输出结果:
```c
int main() {
char str[1024];
Polynomial *P = create_polynomial();
while (fgets(str, sizeof(str), stdin) != NULL) {
Polynomial *Q = parse_polynomial(str);
Polynomial *R = add_polynomial(P, Q);
destroy_polynomial(P);
destroy_polynomial(Q);
P = R;
}
print_polynomial(P);
destroy_polynomial(P);
return 0;
}
```
完整代码如下:
阅读全文