用c语言实现两个一元多项式的加和
时间: 2023-11-18 15:06:37 浏览: 79
c语言链表实现两个一元递增多项式的相加.zip
```c
#include <stdio.h>
#include <stdlib.h>
struct node{
float coef; //系数
int expn; //指数
struct node *next; //指向下一个节点的指针
};
void create_polynomial(struct node **head, int n)
{
struct node *tail = *head;
for(int i = 0; i < n; i++){
struct node *p = (struct node *)malloc(sizeof(struct node));
scanf("%f%d", &p->coef, &p->expn);
p->next = NULL;
if(*head == NULL){
*head = p;
tail = p;
}
else{
tail->next = p;
tail = p;
}
}
}
void print_polynomial(struct node *head)
{
if(head == NULL){
printf("0 0\n");
return;
}
while(head != NULL){
printf("%.1f %d", head->coef, head->expn);
head = head->next;
if(head != NULL){
printf(" ");
}
}
printf("\n");
}
void add_polynomial(struct node *p1, struct node *p2, struct node **p3)
{
while(p1 != NULL && p2 != NULL){
if(p1->expn > p2->expn){
struct node *p = (struct node *)malloc(sizeof(struct node));
p->coef = p1->coef;
p->expn = p1->expn;
p->next = NULL;
if(*p3 == NULL){
*p3 = p;
}
else{
struct node *tail = *p3;
while(tail->next != NULL){
tail = tail->next;
}
tail->next = p;
}
p1 = p1->next;
}
else if(p1->expn < p2->expn){
struct node *p = (struct node *)malloc(sizeof(struct node));
p->coef = p2->coef;
p->expn = p2->expn;
p->next = NULL;
if(*p3 == NULL){
*p3 = p;
}
else{
struct node *tail = *p3;
while(tail->next != NULL){
tail = tail->next;
}
tail->next = p;
}
p2 = p2->next;
}
else{
struct node *p = (struct node *)malloc(sizeof(struct node));
p->coef = p1->coef + p2->coef;
p->expn = p1->expn;
p->next = NULL;
if(*p3 == NULL){
*p3 = p;
}
else{
struct node *tail = *p3;
while(tail->next != NULL){
tail = tail->next;
}
tail->next = p;
}
p1 = p1->next;
p2 = p2->next;
}
}
while(p1 != NULL){
struct node *p = (struct node *)malloc(sizeof(struct node));
p->coef = p1->coef;
p->expn = p1->expn;
p->next = NULL;
if(*p3 == NULL){
*p3 = p;
}
else{
struct node *tail = *p3;
while(tail->next != NULL){
tail = tail->next;
}
tail->next = p;
}
p1 = p1->next;
}
while(p2 != NULL){
struct node *p = (struct node *)malloc(sizeof(struct node));
p->coef = p2->coef;
p->expn = p2->expn;
p->next = NULL;
if(*p3 == NULL){
*p3 = p;
}
else{
struct node *tail = *p3;
while(tail->next != NULL){
tail = tail->next;
}
tail->next = p;
}
p2 = p2->next;
}
}
int main()
{
struct node *head1 = NULL;
struct node *head2 = NULL;
struct node *head3 = NULL;
int n1, n2;
scanf("%d", &n1);
create_polynomial(&head1, n1);
scanf("%d", &n2);
create_polynomial(&head2, n2);
add_polynomial(head1, head2, &head3);
print_polynomial(head3);
return 0;
}
```
阅读全文