|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
//定义链表结构
struct Node {
int data;
struct Node* next;
};
//查找链表中第i个元素的函数
void findElement(struct Node* head, int i){
struct Node* current = head->next;
int index = 1;
while (current != NULL && index < i){
current = current->next;
index++;
}
if (current == NULL || index != i) {
printf("不存在该元素\n");
}else {
printf("第 %d 个元素的值为 %d\n", i, current->data);
}
}
int main() {
struct Node* head = (struct Node*)malloc(sizeof(struct)); //为什么这里报错[Error] expected ')' before 'struct'
head->next = NULL;
//在链表中插入一些元素,这里假设有5个元素
for (int i = 1; i <= 5; i++){
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = i*10; //假设元素值是10的倍数
newNode->next = head->next;
head->next = newNode;
}
//要查找的位置
int i;
printf("请输入要查找的位置(1 ≤ i ≤ 5):");
scanf("%d", &i);
//调用查找函数
findElement(head, i);
//释放链表节点的内存
struct Node* current = head->next;
while (current != NULL){
struct Node* temp = current;
current = current->next;
free(temp);
}
free(head);
return 0;
}
问题见于int main()下面第一个注释,求大佬解惑
在main函数中,为了创建一个新的链表头节点,需要使用malloc函数来分配内存空间。但是在代码中,malloc函数的参数是struct,而不是struct Node。因此,在struct之前应该加上Node,即应该为sizeof(struct Node)。修改代码如下:
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
|
|