如何用c语言创建一个一元多项式的链表
时间: 2024-12-19 11:12:21 浏览: 5
在C语言中,你可以使用链表来存储一元多项式的系数和对应的变量指数。这种设计通常称为“散列链接”或“动态数组”,因为链表节点的内存分配可以根据需要动态调整。下面是创建和操作一元多项式链表的基本步骤:
1. **定义链表节点结构**:
```c
typedef struct Term {
int coefficient;
int exponent;
struct Term* next; // 指向下一个节点的指针
} Term;
```
2. **创建链表**:
```c
Term* create_polynomial() {
return NULL; // 初始化链表为空
}
Term* insert_term(Term* list, int coefficient, int exponent) {
Term* new_term = (Term*)malloc(sizeof(Term));
if (new_term == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
new_term->coefficient = coefficient;
new_term->exponent = exponent;
new_term->next = list;
return new_term;
}
```
3. **添加多项式项**:
```c
Term* add_terms(Term* poly1, Term* poly2) {
Term* current1 = poly1;
Term* current2 = poly2;
while (current1 != NULL && current2 != NULL) {
Term* merged = insert_term(NULL, current1->coefficient + current2->coefficient, current1->exponent);
if (merged == NULL) return NULL;
current1 = current1->next;
current2 = current2->next;
}
// 如果其中一个链表还有剩余项,则追加剩下的部分
if (current1 != NULL) {
while (current1 != NULL) {
merged = insert_term(NULL, current1->coefficient, current1->exponent);
if (merged == NULL) return NULL;
current1 = current1->next;
}
} else if (current2 != NULL) {
while (current2 != NULL) {
merged = insert_term(NULL, current2->coefficient, current2->exponent);
if (merged == NULL) return NULL;
current2 = current2->next;
}
}
return list;
}
```
4. **遍历和打印多项式**:
```c
void print_polynomial(Term* list) {
Term* current = list;
while (current != NULL) {
printf("%d*x^%d + ", current->coefficient, current->exponent);
current = current->next;
}
printf("0\n"); // 输出结束符
}
```
阅读全文