#include
#pragma warning(disable : 4996)
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
struct Node* insertNode = NULL;
void InsertListBegin(int data)
{
struct Node* insertNode = (struct Node*)malloc(sizeof(struct Node*));
if (insertNode == NULL)
{
puts("内存分配失败");
exit(0);
}
else
{
insertNode->data = data;// 这一步过不去
insertNode -> next = head;
head = insertNode;
printf("节点已经插入");
}
};
int main(void)
{
int inputData;
printf("请输入一个整数\n");
scanf("%d", &inputData);
InsertListBegin(inputData);
return 0;
}
struct Node* insertNode = (struct Node*)malloc(sizeof(struct Node*));
改为
struct Node* insertNode = (struct Node*)malloc(sizeof(struct Node));
在分配内存里面是struct Node,而不是指针型类。
小修改了一下。自己试试看。
#include<stdio.h>
#pragma warning(disable : 4996)
struct Node
{
int data;
struct Node *next;
};
struct Node *head=NULL;
struct Node *insertNode = NULL;
void InsertListBegin(int data)
{
struct Node *insertNode = (struct Node *)malloc(sizeof(struct Node));
if (insertNode == NULL)
{
puts("内存分配失败");
exit(0);
}
else
{
insertNode->data = data; // 这一步过不去
insertNode->next = head;
head = insertNode;
printf("节点已经插入\n");
}
};
int main(void)
{
int inputData;
printf("请输入一个整数\n");
scanf("%d", &inputData);
InsertListBegin(inputData);
InsertListBegin(2);
InsertListBegin(3);
InsertListBegin(4);
struct Node *p = head;
printf("\n遍历输出链表数据:\nhead-->\n");
while (p)
{
if(p->next==NULL)
{
printf("%d-->NULL\n",p->data);
}
else
printf("%d-->\n",p->data);
p=p->next;
}
return 0;
}
供参考:
#pragma warning(disable : 4996)
#include<stdio.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head = NULL;
//struct Node *insertNode = NULL; 修改
void InsertListBegin(int data)
{
struct Node *insertNode = (struct Node *)malloc(sizeof(struct Node));
//struct Node* insertNode = (struct Node*)malloc(sizeof(struct Node*));修改
if (insertNode == NULL)
{
puts("内存分配失败");
exit(0);
}
else
{
insertNode->data = data; //这一步过不去
insertNode->next = head;
head = insertNode;
printf("节点已经插入\n");
}
}//; 修改
int main(void)
{
int inputData;
printf("请输入一个整数\n");
scanf("%d", &inputData);
InsertListBegin(inputData);
return 0;
}