用C语言构造两个按指数递增的有序链表,实现两个一元多项式相加,用
时间: 2024-11-15 13:33:58 浏览: 22
在C语言中,我们可以使用结构体来表示一个多项式的项,包括系数和指数,并使用链表数据结构存储这些项。为了构建两个按指数递增的有序链表,我们需要创建一个节点结构,然后分别维护两个链表。当需要添加一元多项式时,我们只需按照指数排序链表并合并。
首先,定义一个节点结构:
```c
typedef struct {
int coefficient; // 系数
int exponent; // 指数
struct Node* next; // 下一个节点指针
} Term;
```
接着,实现链表相关的操作,如插入、比较和合并:
1. 插入函数用于在链表中插入新的项(按指数递增):
```c
void insert(Term** head, int coefficient, int exponent) {
if (*head == NULL || exponent > (*head)->exponent) {
Term* newNode = (Term*)malloc(sizeof(Term));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = *head;
*head = newNode;
} else {
Term* current = *head;
while (current->next != NULL && current->next->exponent < exponent) {
current = current->next;
}
if (current->next == NULL) {
Term* newNode = (Term*)malloc(sizeof(Term));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = current->next;
current->next = newNode;
} else {
newNode = current->next;
current->next = newNode;
newNode->coefficient += coefficient;
}
}
}
```
2. 合并两个有序链表:
```c
Term* mergeLists(Term* list1, Term* list2) {
Term* mergedHead = NULL;
Term* temp;
if (list1 == NULL) return list2;
else if (list2 == NULL) return list1;
if (list1->exponent < list2->exponent) {
mergedHead = list1;
temp = list1->next;
list1->next = list2;
} else {
mergedHead = list2;
temp = list2->next;
list2->next = list1;
}
while (temp != NULL) {
if (temp->exponent < mergedHead->exponent || (temp->exponent == mergedHead->exponent && temp->coefficient <= mergedHead->coefficient)) {
Term* newNode = (Term*)malloc(sizeof(Term));
newNode->coefficient = temp->coefficient;
newNode->exponent = temp->exponent;
newNode->next = mergedHead->next;
mergedHead->next = newNode;
temp = mergedHead->next;
} else {
temp = temp->next;
}
}
return mergedHead;
}
```
最后,你可以通过这两个函数来实现两个一元多项式的相加:
```c
Term* addPolynomials(Term* poly1, Term* poly2) {
return mergeLists(poly1, poly2);
}
// 示例
Term* list1 = NULL;
insert(&list1, 1, 0); // x^0 + 1
insert(&list1, 2, 2); // x^2 + 2x^0
Term* list2 = NULL;
insert(&list2, 3, 1); // x^1 + 3x^0
Term* result = addPolynomials(list1, list2);
// 输出结果
while (result != NULL) {
printf("%.0fx^%d + ", result->coefficient, result->exponent);
result = result->next;
}
printf("\n");
```
阅读全文