適合初學者參考,採用鏈表儲存多項式節點 (係數、指數、下一節點),實現建立、相加、列印功能。
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#define LEN sizeof(node)
typedef struct polynode {
int coef; // 係數
int exp; // 指數
struct polynode *next; // 下一項
} node;
node *create(void) {
node *h, *r, *s;
int c, e;
h = (node *)malloc(LEN); r = h;
printf("coef:"); scanf("%d", &c);
printf("exp: "); scanf("%d", &e);
while (c != 0) {
s = (node *)malloc(LEN);
s->coef = c; s->exp = e;
r->next = s; r = s;
printf("coef:"); scanf("%d", &c);
printf("exp: "); scanf("%d", &e);
}
r->next = NULL;
return h;
}
輸入係數為 0 結束。帶表頭節點,h 為表頭,r 尾指標。
void polyadd(node *polya, node *polyb) {
node *p, *q, *pre, *temp;
int sum;
p = polya->next; q = polyb->next; pre = polya;
while (p != NULL && q != NULL) {
if (p->exp < q->exp) { // A 指數較小,接入結果
pre->next = p; pre = p; p = p->next;
} else if (p->exp == q->exp) { // 指數相同,係數相加
sum = p->coef + q->coef;
if (sum != 0) {
p->coef = sum;
pre->next = p; pre = p;
p = p->next; temp = q; q = q->next; free(temp);
} else { // 係數抵銷,刪除兩節點
temp = p->next; free(p); p = temp;
temp = q->next; free(q); q = temp;
}
} else { // B 指數較小,接入結果
pre->next = q; pre = q; q = q->next;
}
}
if (p != NULL) pre->next = p;
else pre->next = q;
}
就地修改 polya 為結果,釋放多餘節點。
void print(node *p) {
while (p->next != NULL) {
p = p->next;
printf(" %d*x^%d", p->coef, p->exp);
}
}
int main() {
node *polya, *polyb;
printf("Welcome!\n");
printf("Input polya (coef exp):\n"); polya = create(); print(polya);
printf("\nInput polyb (coef exp):\n"); polyb = create(); print(polyb);
printf("\nSum:\n"); polyadd(polya, polyb); print(polya);
return 0;
}