void create(struct node *head); //declaring functions
void display(struct node *head);
struct node //creating a struct datatype for nodes
{
int coeff;
int power;
struct node* next;
};
struct node* poly1=NULL; //head pointer for a sample polynomial
void main()
{
int coeff,power,deg,i;
clrscr(); //main function
printf("\n enter polynomial 1 ");
create(poly1);
display(poly1);
getch();
}
void create(struct node *head)
{
struct node *newnode,*temp;
int exp,num,n,i;
printf("\n enter no. of terms in your expression=");
scanf("%d",&n);
for(i=0;i<n;i++)
{
newnode=(struct node*)malloc(sizeof(newnode));
newnode->next=NULL;
printf("\n enter power=");
scanf("%d",&exp);
newnode->power=exp;
printf("\n enter coefficient=");
scanf("%d",&num);
newnode->coeff=num;
if(head==NULL)
head=newnode;
else
{
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
}
}
void display(struct node *head)
{
struct node *temp;
temp=head;
while(temp->next!=NULL)
{
printf("%dx^%d",temp->coeff,temp->power);
temp=temp->next;
}
}
我的代码编译没有显示错误或警告,但我无法打印我的多项式函数。显示功能仅打印 0 x^ 0 或根本不打印任何值,我尝试了很多方法但它不起作用,有人可以指出我应该做什么来纠正它。我用的是C语言。
最佳答案
My code compilation shows no errors or warnings
这很奇怪。添加缺少的包含并注释掉 getch
和 clrscr
后,这是编译器输出,甚至没有启用(几乎强制)标志 -Wall -Wextra
:
$ gcc main.c
main.c:4:20: warning: ‘struct node’ declared inside parameter list will not be visible outside of this definition or declaration
4 | void create(struct node *head); //declaring functions
| ^~~~
main.c:5:21: warning: ‘struct node’ declared inside parameter list will not be visible outside of this definition or declaration
5 | void display(struct node *head);
| ^~~~
main.c: In function ‘main’:
main.c:19:11: warning: passing argument 1 of ‘create’ from incompatible pointer type [-Wincompatible-pointer-types]
19 | create(poly1);
| ^~~~~
| |
| struct node *
main.c:4:26: note: expected ‘struct node *’ but argument is of type ‘struct node *’
4 | void create(struct node *head); //declaring functions
| ~~~~~~~~~~~~~^~~~
main.c:20:12: warning: passing argument 1 of ‘display’ from incompatible pointer type [-Wincompatible-pointer-types]
20 | display(poly1);
| ^~~~~
| |
| struct node *
main.c:5:27: note: expected ‘struct node *’ but argument is of type ‘struct node *’
5 | void display(struct node *head);
| ~~~~~~~~~~~~~^~~~
main.c: At top level:
main.c:24:8: error: conflicting types for ‘create’
24 | void create(struct node *head)
| ^~~~~~
main.c:4:6: note: previous declaration of ‘create’ was here
4 | void create(struct node *head); //declaring functions
| ^~~~~~
main.c:53:7: error: conflicting types for ‘display’
53 | void display(struct node *head)
| ^~~~~~~
main.c:5:6: note: previous declaration of ‘display’ was here
5 | void display(struct node *head);
您的编译器似乎严重过时。
您的代码似乎有很多问题,但一个明显的问题是:
newnode=(struct node*)malloc(sizeof(newnode));
强制转换是不好的做法,但不应导致任何实际问题,但 sizeof 的参数是错误的。应该是:
newnode=malloc(sizeof(*newnode));
关于c - 我无法使用链表打印多项式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59371061/