【一元多项式算法】设一个一元多项式采用带头结点的单链表存储,所有结点
按照升幂方式链接。设计一个算法,求两个多项式 A 和 B 的乘积,结果多项式 C
存放在新辟的空间中。
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int coef;
int expn;
struct node* next;
}node;
struct node* create(int n) {
int i, num, g;
struct node* ptr = NULL, * head = NULL, * tail = NULL;
printf("Input %d data:\n", n);
for (i = 0; i < n; i++)
{
scanf_s("%d %d", &num, &g);
ptr = (struct node*)malloc(sizeof(struct node));
ptr->coef = num;
ptr->expn = g;
ptr->next = NULL;
if (head == NULL) head = ptr;
else tail->next = ptr;
tail = ptr;
}
return head;
}
struct node* Multiply(node* L1, node* L2) {
int temp;
node* ptr=NULL, * head=NULL, * tail=NULL, * ptr1=NULL, * ptr2=NULL;
for (ptr1 = L1; ptr1 != NULL; ptr1 = ptr1->next) {
for (ptr2 = L2; ptr2 != NULL; ptr2 = ptr2->next) {
ptr = (node*)malloc(sizeof(node));
ptr->coef = (ptr1->coef) * (ptr2->coef);
ptr->expn = ptr1->expn + ptr2->expn;
ptr->next = NULL;
if (head == NULL)head = ptr;
else tail->next = ptr;
tail = ptr;
}
}
for (ptr1 = head; ptr1 != NULL; ptr1 = ptr1->next) {
for (ptr2 = ptr1->next, tail = ptr1; ptr2 != NULL;) {
if (ptr1->expn == ptr2->expn) {
ptr1->coef = ptr1->coef + ptr2->coef;
tail->next = ptr2->next;
free(ptr2);
ptr2 = tail->next;
}
else {
tail = ptr2;
ptr2 = ptr2->next;
}
}
}
for (ptr1 = head; ptr1->next != NULL; ptr1 = ptr1->next) {
for (ptr2 = ptr1->next; ptr2 != NULL; ptr2 = ptr2->next) {
if (ptr1->expn < ptr2->expn) {
temp = ptr1->expn;
ptr1->expn = ptr2->expn;
ptr2->expn = temp;
temp = ptr1->coef;
ptr1->coef = ptr2->coef;
ptr2->coef = temp;
}
}
}
for (ptr = head; ptr != NULL;) {
if (ptr->coef==0) {
if (ptr == head) {
head = head->next;
free(ptr);
ptr = head;
}
else {
ptr1->next = ptr->next;
free(ptr);
ptr = ptr1->next;
}
}
else {
ptr1 = ptr;
ptr = ptr->next;
}
}
return head;
}
void print(node* L) {
node* p;
p = L;
while (p!=NULL) {
printf("%d %d\n", p->coef, p->expn);
p= p->next;
}
}
int main() {
int n1, n2;
node* L1, * L2, * L;
printf("Input n1:");
scanf_s("%d", &n1);
L1 = create(n1);
printf("Input n2:");
scanf_s("%d", &n2);
L2 = create(n2);
L = Multiply(L1, L2);
printf("结果为:\n");
print(L);
}