# include <stdio.h>
# include <malloc.h>
# include <stdlib.h>
# define MAXLEN 40
typedef struct Node
{
int exp;
float coe;
}* PNODE, NODE;
typedef struct
{
PNODE term;
}* PLIST, LIST;
void init (PLIST pL)
{
pL->term = (PNODE)malloc(sizeof(NODE) * MAXLEN);
if (!pL->term)
{
printf("内存分配失败!\n");
exit(-1);
}
pL->term[0].exp = 0;
return;
}
void create (PLIST pL)
{
char ch = 'N';
int i = 1;
while (ch != 'Y' && ch != 'y')
{
printf("输入第%d项的指数:", i);
scanf("%d", &(pL->term[i].exp));
printf("输入第%d项的指数:", i);
scanf("%f", &(pL->term[i].coe));
//printf("%f\n", pL->term[i].coe); //没有这行运行会奔溃,有了这行或者编译后注释掉这行再运行也不会奔溃
//什么原因啊
++i;
printf("是否完成(Y/N):");
scanf(" %c", &ch);
}
pL->term[0].exp = i - 1;
return;
}
void arr (PLIST pL)
{
int i, j;
for (i = 1; i < pL->term[0].exp; ++i)
{
for (j = 1; j < pL->term[0].exp - i + 1; ++j)
{
if (pL->term[j].exp > pL->term[j+1].exp)
{
int x = pL->term[j].exp;
float f = pL->term[j].coe;
pL->term[j].exp = pL->term[j+1].exp;
pL->term[j].coe = pL->term[j+1].coe;
pL->term[j+1].exp = x;
pL->term[j+1].coe = f;
}
}
}
return;
}
void add (PLIST pL1, PLIST pL2, PLIST pL3)
{
int i = 1;
int j = 1;
int k = 1;
while (i <= pL1->term[0].exp && j <= pL2->term[0].exp)
{
if (pL1->term[i].exp < pL2->term[j].exp)
{
pL3->term[k].exp = pL1->term[i].exp;
pL3->term[k].coe = pL1->term[i].coe;
++i;
++k;
}
else if (pL1->term[i].exp > pL2->term[j].exp)
{
pL3->term[k].exp = pL2->term[j].exp;
pL3->term[k].coe = pL2->term[j].coe;
++j;
++k;
}
else
{
pL3->term[k].exp = pL1->term[i].exp;
pL3->term[k].coe = pL1->term[i].coe + pL2->term[j].coe;
++i;
++j;
++k;
}
}
if (i > pL1->term[0].exp)
{
while (j <= pL2->term[0].exp)
{
pL3->term[k].exp = pL2->term[j].exp;
pL3->term[k].coe = pL2->term[j].coe;
++j;
++k;
}
}
if (j > pL2->term[0].exp)
{
while (i <= pL1->term[0].exp)
{
pL3->term[k].exp = pL1->term[i].exp;
pL3->term[k].coe = pL1->term[i].coe;
++i;
++k;
}
}
pL3->term[0].exp = k - 1;
return;
}
void multiply (PLIST pL1, PLIST pL2, PLIST pL3)
{
int i, j, x;
int k = 1;
for (i = 1; i <= pL1->term[0].exp; ++i)
{
for (j = 1; j <= pL2->term[0].exp; ++j)
{
int a = pL1->term[i].exp + pL2->term[j].exp;
float f = pL1->term[i].coe * pL2->term[j].coe;
x = 1;
while (a > pL3->term[x].exp && x++ <= pL3->term[0].exp);
if (a == pL3->term[x].exp)
{
pL3->term[x].coe += f;
continue;
}
else
{
pL3->term[k].exp = a;
pL3->term[k].coe = f;
++pL3->term[0].exp;
++k;
}
}
}
return;
}
void traverse (PLIST pL)
{
for (int i = 1; i <=pL->term[0].exp; ++i)
{
printf("%f, %d\t", pL->term[i].coe, pL->term[i].exp);
}
printf("\n");
return;
}
int main(void)
{
LIST list1;
LIST list2;
LIST list3;
init(&list1);
create(&list1);
arr(&list1);
traverse(&list1);
printf("\n-------------------\n");
init(&list2);
create(&list2);
arr(&list2);
traverse(&list2);
printf("\n-------------------\n");
init(&list3);
add(&list1, &list2, &list3);
traverse(&list3);
printf("\n-------------------\n");
init(&list3);
multiply(&list1, &list2, &list3);
traverse(&list3);
return 0;
}
线性表写一元二次方程组
最新推荐文章于 2022-11-20 20:55:29 发布