这个c代码(链表实现)有什么问题?

时间:2015-11-13 15:16:07

标签: c linked-list singly-linked-list

 //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));
                             ^

2 个答案:

答案 0 :(得分:6)

  1. node*在C语境中与struct node*不同,与C ++相同。

  2. 尽量避免使用C.中的多余演员表。实际上,尽量避免使用任何不需要的语言的多余演员阵容。 Do I cast the result of malloc?

答案 1 :(得分:1)

更改以下声明

struct node* temp=(node*)malloc(sizeof(struct node));

成,

struct node* temp=(struct node*)malloc(sizeof(struct node));

有时候我也犯了类似的错误。