C语言中使用链表实现多项式相加
时间: 2023-05-25 11:06:29 浏览: 151
C语言单链表实现多项式相加
具体步骤如下:
1. 定义一个结构体来存储一个多项式的每一项。
```
struct node{
float coef; // 系数
int expn; // 指数
struct node *next; // 指向下一个节点的指针
};
```
2. 定义一个函数来创建一个多项式。该函数将一个字符串作为输入,将其转换为一个多项式存储在链表中。
```
struct node* create(char* str){
struct node *head, *p, *q;
head = (struct node*)malloc(sizeof(struct node)); // 分配头节点的空间
head->coef = 0;
head->expn = 0;
head->next = NULL;
p = head;
while(*str){
q = (struct node*)malloc(sizeof(struct node)); // 分配新节点的空间
q->coef = atof(str);
while(*str != ' ') str++; // 跳过系数部分
q->expn = atoi(++str);
while(*str != ' ' && *str) str++; // 跳过指数部分
p->next = q;
p = q;
}
p->next = NULL;
return head;
}
```
3. 定义一个函数来打印一个多项式。
```
void print(struct node* head){
struct node *p = head->next;
while(p){
printf("%.2fx^%d ", p->coef, p->expn);
p = p->next;
}
printf("\n");
}
```
4. 定义一个函数来将两个多项式相加。该函数接收两个链表指针,返回一个链表指针。
```
struct node* add(struct node* head1, struct node* head2){
struct node *p = head1->next, *q = head2->next, *r, *s;
struct node *head = (struct node*)malloc(sizeof(struct node));
head->coef = 0;
head->expn = 0;
head->next = NULL;
s = head;
while(p && q){
r = (struct node*)malloc(sizeof(struct node));
if(p->expn < q->expn){
r->coef = p->coef;
r->expn = p->expn;
p = p->next;
}
else if(p->expn > q->expn){
r->coef = q->coef;
r->expn = q->expn;
q = q->next;
}
else{
r->coef = p->coef + q->coef;
r->expn = p->expn;
p = p->next;
q = q->next;
}
s->next = r;
s = r;
}
while(p){
r = (struct node*)malloc(sizeof(struct node));
r->coef = p->coef;
r->expn = p->expn;
p = p->next;
s->next = r;
s = r;
}
while(q){
r = (struct node*)malloc(sizeof(struct node));
r->coef = q->coef;
r->expn = q->expn;
q = q->next;
s->next = r;
s = r;
}
s->next = NULL;
return head;
}
```
5. 测试函数。
```
int main(){
struct node *head1, *head2, *head3;
char str1[50], str2[50];
printf("请输入第一个多项式:");
fgets(str1, 50, stdin);
printf("请输入第二个多项式:");
fgets(str2, 50, stdin);
head1 = create(str1);
head2 = create(str2);
head3 = add(head1, head2);
printf("第一个多项式:");
print(head1);
printf("第二个多项式:");
print(head2);
printf("相加结果:");
print(head3);
return 0;
}
```
阅读全文