두 다항식의 곱셈 연산
#include <stdio.h>
#include <stdlib.h>
float coef;
typedef struct Listnode {
float coef;
int expo;
struct Listnode* link;
}Listnode;
typedef struct Listhead {
Listnode* head;
}Listhead;
Listhead* createlinkedlist(void){
Listhead* L;
L = (Listhead *)malloc(sizeof(Listhead));
L->head = NULL;
return L;
}
void appendTerm(Listhead* L, float coef, int expo){
Listnode* newnode;
Listnode* p;
newnode = (Listnode *)malloc(sizeof(Listnode));
newnode->coef = coef;
newnode->expo = expo;
newnode->link = NULL;
if (L->head == NULL){
L->head = newnode;
return;
}
else {
p = L->head;
while (p->link != NULL) {
p = p->link;
}
p->link = newnode;
}
}
void mulpoly(Listhead* A, Listhead* B, Listhead* C){
Listnode* pA = A->head;
Listnode* pB = B->head;
float sum;
int exposum;
while (pA){
while (pB){
sum = pA->coef * pB->coef;
exposum = pA->expo + pB->expo;
appendTerm(C, sum, exposum);
pB = pB->link;
}
pA = pA->link;
pB = B->head;
}
}
void printpoly(Listhead* L){
Listnode* p = L->head;
for (; p; p = p->link){
printf("%3.0fx^%d", p->coef, p->expo);
if(p->link != NULL) printf(" +");
}
}
void main(void){
Listhead *A, *B, *C;
A = createlinkedlist();
B = createlinkedlist();
C = createlinkedlist();
appendTerm(A, 5, 3);
appendTerm(A, 4, 2);
appendTerm(A, 3, 1);
printf("\n A(x) =");
printpoly(A);
appendTerm(B, 3, 3);
appendTerm(B, 2, 2);
appendTerm(B, 1, 1);
printf("\n B(x) =");
printpoly(B);
mulpoly(A, B, C);
printf("\n C(x) =");
printpoly(C);
getchar();
}