我正在尝试使用链表和循环表示来实现多项式,即最后一个节点指向第一个节点(标题)的链接。当我使用函数 create
创建第一个多项式时,所有链接都完美建立,包括最后一个循环链接。然而,当我使用相同的函数“创建”创建第二个多项式时,第一个多项式的圆形链接就会断开。 (第一个多项式的所有其他链接保持不变)。我正在使用 TurboC++ 编译器(我已使用 .c
扩展名保存了我的文件。)
创建函数如下:
void create(poly header)
{
poly temp;
int i,n;
temp=header;
printf("\nEnter the number of terms: "); scanf("%d",&n);
if(n==0)
{
header->link=header;
return;
}
printf("\nEnter the coefficients and exponents:\n");
for(i=0;i<n;i++)
{
temp->link=malloc(sizeof(poly));
temp=temp->link;
printf("\nCoef: "); scanf("%d",&temp->coef);
printf("Exp : "); scanf("%d",&temp->exp);
if(i==n-1)
temp->link=header;
}
}
主要功能如下:
void main()
{
clrscr();
header1=malloc(sizeof(poly));
header2=malloc(sizeof(poly));
printf("Polynomial 1:\n");
create(header1);
printf("\nPolynomial 2:\n");
create(header2);
printf("\n\nP1: ");
display(header1);
printf("\n\nP2: ");
display(header2);
getch();
}
显示函数如下:
void display(poly header)
{
poly temp;
if(header->link==header)
printf("Zero polynomial\n");
temp=header->link;
while(temp!=header)
{
if(temp->exp==header->link->exp||temp->coef<0)
printf("%d(x^%d)",temp->coef,temp->exp);
else
printf(" + %d(x^%d)",temp->coef,temp->exp);
temp=temp->link;
}
}
create
和 display
函数都可以完美运行;我已经通过创建一个多项式并打印它来进行检查。
我已经跟踪了程序并检查了链接(我分别使用多项式 3x^2+2x+1 和 2x^2+1 作为我的第一个和第二个多项式)。
这就是我完成声明的方式:
struct POLY
{
int coef,exp;
struct POLY *link;
};
typedef struct POLY* poly;
poly header1=NULL,header2=NULL,header3=NULL; //global
我的问题可能听起来微不足道,但请帮助我。我是使用链接列表的新手。
最佳答案
如果 poly
是指针类型,那么您的 malloc()
可能会分配错误的内存量。 ——约翰·博林格
我刚刚在 malloc() 中将“poly”替换为“struct POLY”,并获得了所需的输出。 – 阿琼·德赛
关于c - 当我使用链表和循环表示实现多项式时,循环链接会断开。谁能告诉我为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26507767/