用单链表表示一元多项式,并实现输入、输出、加、减运算。…… 要求实现: (1)创建多项式 (2)多项式加法 (3)输出多项式 (4)多项式减法 用c语言 没有指数
时间: 2024-11-16 16:20:42 浏览: 6
完成多项式的相加运算
5星 · 资源好评率100%
在C语言中,我们可以使用结构体和单链表来表示一元多项式。首先,我们需要定义一个`Term`结构体来存储每个项,包括系数和变量(在这里我们假设是一次多项式,所以只有一个变量x):
```c
typedef struct {
double coefficient; // 系数
int variable; // 变量,这里为1,因为我们只考虑一次多项式
} Term;
typedef struct Polynomial {
Term* head;
int degree;
} Polynomial;
```
接下来,我们实现一些基本操作:
1. **创建多项式** (`createPolynomial`):
- 初始化链表头节点,设置度为0。
```c
Polynomial* createPolynomial(double a) {
Polynomial* poly = (Polynomial*)malloc(sizeof(Polynomial));
poly->head = (Term*)malloc(sizeof(Term));
poly->head->coefficient = a;
poly->head->variable = 1;
poly->degree = 1;
return poly;
}
```
2. **多项式加法** (`addPolynomials`):
- 遍历两个多项式的链表,累加对应系数的项。
```c
Polynomial* addPolynomials(Polynomial* p1, Polynomial* p2) {
Polynomial* result = createPolynomial(0);
Term* cur1 = p1->head;
Term* cur2 = p2->head;
while (cur1 && cur2) {
if (cur1->coefficient > cur2->coefficient)
result->head->coefficient += cur1->coefficient, cur1++;
else
result->head->coefficient += cur2->coefficient, cur2++;
}
while (cur1) {
result->head->coefficient += cur1->coefficient;
cur1++;
}
while (cur2) {
result->head->coefficient += cur2->coefficient;
cur2++;
}
result->degree = MAX(p1->degree, p2->degree);
return result;
}
```
3. **输出多项式** (`displayPolynomial`):
- 从头节点开始遍历并打印系数。
```c
void displayPolynomial(Polynomial* poly) {
printf("Polynomial: ");
Term* temp = poly->head;
while (temp) {
printf("%.2f*x^1 + ", temp->coefficient);
temp = temp->next;
}
printf("\n");
}
```
4. **多项式减法** (`subtractPolynomials`):
- 类似于加法,只是需要判断是相加还是相减。
```c
Polynomial* subtractPolynomials(Polynomial* p1, Polynomial* p2) {
Polynomial* result = createPolynomial(0);
Term* cur1 = p1->head;
Term* cur2 = p2->head;
while (cur1 && cur2) {
if (cur1->coefficient > cur2->coefficient)
result->head->coefficient = cur1->coefficient - cur2->coefficient, cur1++;
else
result->head->coefficient = cur2->coefficient - cur1->coefficient, cur2++;
}
while (cur1) {
result->head->coefficient -= cur1->coefficient;
cur1++;
}
while (cur2) {
result->head->coefficient -= cur2->coefficient;
cur2++;
}
result->degree = MAX(p1->degree, p2->degree);
return result;
}
```
请注意,这个实现假定`Term`结构体有一个`next`指针来连接下一个项。上述函数可能会导致内存泄漏,如果在不再需要链表时忘记释放内存,建议在实际项目中适当优化。以下是完整的示例:
```c
//... 其他必要的库函数声明 ...
int main() {
Polynomial* poly1 = createPolynomial(5);
Polynomial* poly2 = createPolynomial(3);
Polynomial* sum = addPolynomials(poly1, poly2);
Polynomial* diff = subtractPolynomials(poly1, poly2);
displayPolynomial(poly1);
displayPolynomial(poly2);
displayPolynomial(sum);
displayPolynomial(diff);
freePolyList(&poly1);
freePolyList(&poly2);
freePolyList(&sum);
freePolyList(&diff);
return 0;
}
void freePolyList(Polynomial** poly) {
if (*poly != NULL) {
Term* temp = (*poly)->head;
while (temp != NULL) {
Term* next = temp->next;
free(temp);
temp = next;
}
free(*poly);
*poly = NULL;
}
}
```
阅读全文