如何解决我在使用单向链表的这个“在列表开头插入节点”中找不到错误
我在 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,即
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
感谢您提出这个问题。
,同样的代码适用于导师,因为他使用的是 C++ 编译器,而在您的情况下,您使用的是 C 编译器。
为了使用 c 编译器进行编译,修改第 12 行如下。
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
在 C 中,无论何时声明 struct 数据类型,都必须使用 struct 关键字。 C++ 不是这种情况。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。