c语言构造两个按指数递增的有序链表,实现两个一元多项式相加
时间: 2024-06-13 18:07:03 浏览: 81
c语言链表实现两个一元递增多项式的相加.zip
以下是C语言实现两个按指数递增的有序链表,实现两个一元多项式相加的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int coef; // 系数
int expn; // 指数
struct node *next;
} Node, *Polynomial;
void CreatePolyn(Polynomial *P, int m) {
*P = (Polynomial) malloc(sizeof(Node));
(*P)->next = NULL;
Node *r = *P;
for (int i = 0; i < m; i++) {
Node *p = (Node *) malloc(sizeof(Node));
scanf("%d %d", &p->coef, &p->expn);
p->next = NULL;
r->next = p;
r = p;
}
}
void AddPolyn(Polynomial *Pa, Polynomial *Pb) {
Node *p = (*Pa)->next, *q = (*Pb)->next, *r = *Pa;
while (p && q) {
if (p->expn < q->expn) {
r->next = p;
r = p;
p = p->next;
} else if (p->expn > q->expn) {
r->next = q;
r = q;
q = q->next;
} else {
p->coef += q->coef;
if (p->coef != 0) {
r->next = p;
r = p;
} else {
Node *temp = p;
p = p->next;
free(temp);
}
Node *temp = q;
q = q->next;
free(temp);
}
}
r->next = p ? p : q;
free(*Pb);
}
void PrintPolyn(Polynomial P) {
Node *p = P->next;
int flag = 0;
while (p) {
if (flag == 0) {
printf("%d %d", p->coef, p->expn);
flag = 1;
} else {
if (p->coef > 0) {
printf(" + %d %d", p->coef, p->expn);
} else {
printf(" - %d %d", -p->coef, p->expn);
}
}
p = p->next;
}
printf("\n");
}
int main() {
Polynomial Pa, Pb;
int m, n;
scanf("%d", &m);
CreatePolyn(&Pa, m);
scanf("%d", &n);
CreatePolyn(&Pb, n);
AddPolyn(&Pa, &Pb);
PrintPolyn(Pa);
return 0;
}
```
阅读全文