|
楼主 |
发表于 2018-12-24 14:24:03
|
显示全部楼层
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
typedef int bool;
typedef struct node
{
int coef, exp;
struct node *next;
} NODE;
NODE * multiplication(NODE *, NODE *);
void input(NODE *);
void output(NODE *);
NODE* Link(NODE* p,int i) //输入头节点,返回第i个节点,i从0算起
{
int j;
for (j = 0; j <= i; j++)
{
p = p->next;
if (p == NULL) return NULL;
}
return p;
}
int Length(NODE* p) //输入头节点,返回长度,
{
int j=0;
while (p->next != NULL)
{
j++;
p = p->next;
}
return j;
}
void Append(NODE* p, int coef0, int exp0) //为一个节点添加后继并重新将指针指向后继,
{
p->next = (NODE*)malloc(sizeof(NODE));
p = p->next;
p->coef = coef0;
p->exp = exp0;
p->next=NULL;
}
void DeleteLinklist(NODE* head) //删除链表
{
NODE *pPre;
while (head != NULL)
{
pPre = head;
head = head->next;
free(pPre);
}
}
NODE * multiplication(NODE *p1, NODE *p2) //乘法运算
{
NODE* ans,*p3;
NODE* Temp1,* Temp2;
p3 = (NODE*)malloc(sizeof(NODE)); //新建链表p3
ans = p3;
int i,j; //ans指向p3的头节点,用于返回
int len = Length(p1) + Length(p2)-1; //p3的最高次项=两链表最高次项相加
for (i = 0; i < len; i++) //依次填充p3的每一项
{
Append(p3, 0, i);
for (j = 0; j <= i; j++)
{
Temp1 = Link(p1,j);
Temp2 = Link(p2, i - j);
if ((Temp1!=NULL)&&(Temp2!=NULL)) p3->coef += (Temp1->coef*Temp2->coef);
}
}
return ans;
}
void input(NODE * p) //输入头节点,读取并储存于链表中
{
int a, b;
int i = 0;
rewind(stdin);
while(scanf_s("<%d,%d>,", &a, &b)) //读取一项,并将值暂时储存于a和b中
{
for (i; i < b; i++) Append(p, 0, i); //延长链表,直到指数=b
Append(p, a, b); //赋值
i++;
}
}
void output(NODE * head)
{
bool b = false; //储存是否已产生有效输出
while (head->next != NULL)
{
head = head->next;
if (head->coef != 0)
{
b = true; //如果任意一项系数不为0,即产生了有效输出
printf("<%d,%d>,", head->coef, head->exp);
}
}
if (!b) printf("<0,0>,"); //如果没有产生有效输出,说明这是个0多项式,输出<0,0>
printf("\n");
}
int main()
{
int i;
NODE * head1, *head2, *head3;
head1 = (NODE *)malloc(sizeof(NODE));
input(head1);
head2 = (NODE *)malloc(sizeof(NODE));
input(head2);
head3 = multiplication(head1, head2);
output(head3);
DeleteLinklist(head1);
DeleteLinklist(head2);
DeleteLinklist(head3);
return 0;
} |
|