我在这个'Inserting node at begining of list'使用单链表找不到错误



我在Youtube/freeCodeCamp.org/data structure上使用C和C++编写了这段代码。同样的代码也适用于导师,但在我的电脑上不起作用。

#include <stdio.h>
#include <stdlib.h>
struct Node
{          
int data;   
struct Node *next; 
};
struct Node *head;
void Insert(int x)
{
struct Node *temp = (Node *)malloc(sizeof(struct Node));
(*temp).data = x;
(*temp).next = head;
head = temp;
};
void Print()
{
struct Node *temp = head;
printf("List is::");
while (temp != NULL)
{
printf("%d", temp->data);
temp = temp->next;
}
printf("n");
};
int main()
{
head = NULL;
printf("How many numbers;n");
int n, x;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("Enter the number;n");
scanf("%d", &x);
Insert(x);
Print();
}
}

编译器输出:

insertingNodeAtbegining.c: In function 'Insert':
insertingNodeAtbegining.c:12:26: error: 'Node' undeclared (first use in this function)
struct Node *temp = (Node *)malloc(sizeof(struct Node));
^~~~
insertingNodeAtbegining.c:12:26: note: each undeclared identifier is reported only once for each 
function it appears in
insertingNodeAtbegining.c:12:32: error: expected expression before ')' token
struct Node *temp = (Node *)malloc(sizeof(struct Node));
^

请在第12行添加数据类型结构体,即

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

谢谢你的提问。

导师使用了相同的代码,因为他使用了C++编译器,而在您的情况下,您使用的是C编译器。

要使用c编译器进行编译,请按如下方式修改第12行。

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

在C中,无论何时声明结构数据类型,都必须使用struct关键字。C++的情况并非如此。

最新更新