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

标签 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));
                             ^

最佳答案

  1. node* 与 C++ 中此上下文中的 struct node* 不同。

  2. 尽量避免在 C 语言中出现多余的强制转换。实际上,在任何不需要强制转换的语言中,尽量避免出现多余的强制转换。 Do I cast the result of malloc?

关于c - 这个c代码(链表实现)有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695927/

相关文章:

c - C 中的链表包含结构体

c - 删除链表中的重复项

C#内存分配和链表实现

c++ - 创建一个指针的指针并在不修改原始指针的情况下对其进行修改?

php - 哪个 PHP 函数使用了这种哈希算法?

c - 使用 PortAudio 录音 : Pa_GetStreamReadAvailable not work?

c - fputs 读取到文件末尾后返回-1

c - 字符指针预增

java - 在头为空的链表中插入

java - Java实现Queue但不能重写iterator()方法