这个c代码(链表实现)有什么问题?
Whats wrong with this c code(linked list implementation)?
//linked list implementation
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void insert(int);
void print();
int main()
{
head=NULL;
int n,i,x;
printf("\nEnter the number of elements :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the element :");
scanf("%d",&x);
insert(x);
print();
}
}
void insert(int x)
{
struct node* temp=(node*)malloc(sizeof(struct node));
temp->data=x;
temp->link=head;
head=temp;
}
void print()
{
struct node* temp=head;
int i=0;
printf("\nThe list is ");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->link;
}
printf("\n");
}
编译代码时:
In function 'insert':
28:24: error: 'node' undeclared (first use in this function)
struct node* temp=(node*)malloc(sizeof(struct node));
^
28:24: note: each undeclared identifier is reported only once for each function it appears in
28:29: error: expected expression before ')' token
struct node* temp=(node*)malloc(sizeof(struct node));
^
更改以下语句
struct node* temp=(node*)malloc(sizeof(struct node));
进入,
struct node* temp=(struct node*)malloc(sizeof(struct node));
有时候我确实会犯类似的错误。
node*
与 C 中此上下文中的 struct node*
不同,因为它适用于 C++。
尽量避免在 C 中进行多余的强制转换。实际上,在任何不需要的语言中尽量避免多余的强制转换。 Do I cast the result of malloc?
//linked list implementation
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
struct node* head;
void insert(int);
void print();
int main()
{
head=NULL;
int n,i,x;
printf("\nEnter the number of elements :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the element :");
scanf("%d",&x);
insert(x);
print();
}
}
void insert(int x)
{
struct node* temp=(node*)malloc(sizeof(struct node));
temp->data=x;
temp->link=head;
head=temp;
}
void print()
{
struct node* temp=head;
int i=0;
printf("\nThe list is ");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->link;
}
printf("\n");
}
编译代码时:
In function 'insert':
28:24: error: 'node' undeclared (first use in this function)
struct node* temp=(node*)malloc(sizeof(struct node));
^
28:24: note: each undeclared identifier is reported only once for each function it appears in
28:29: error: expected expression before ')' token
struct node* temp=(node*)malloc(sizeof(struct node));
^
更改以下语句
struct node* temp=(node*)malloc(sizeof(struct node));
进入,
struct node* temp=(struct node*)malloc(sizeof(struct node));
有时候我确实会犯类似的错误。
node*
与 C 中此上下文中的struct node*
不同,因为它适用于 C++。尽量避免在 C 中进行多余的强制转换。实际上,在任何不需要的语言中尽量避免多余的强制转换。 Do I cast the result of malloc?