马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<winuser.inl>
#include<stdio.h>
#include <cstdlib>
#include<string.h>
//输入学生的总人数以及每个学生的姓名成绩,并将内容打印出来
//用头插法向链表里面添加元素
void getInput(struct Student* stu);
void printfInfo(struct Student**head);
void releaseMemory(struct Student** head);
void head_add(struct Student** head);
struct Student
{
char name[20];
int score;
struct Student *next;
};
void getInput(struct Student *stu)
{
printf("name:");
scanf_s("%s", stu->name, 20);
printf("score:");
scanf_s("%d",&stu->score);
}
void printfInfo(struct Student **head)
{
struct Student* stu;
stu = *head;
while (stu != NULL)
{
printf("name: %s \n", stu->name);
printf("score:%d \n", stu->score);
stu = stu->next;
}
}
void releaseMemory(struct Student** head)
{
struct Student* stu, * temp;
stu = *head;
while (stu != NULL)
{
temp = stu;
stu = stu->next;
free(temp);
}
}
void head_add(struct Student **head)
{
struct Student *stu,*temp;
stu = (struct Student*)(malloc(sizeof(struct Student)));
if (stu == NULL)
{
printf("memory failed");
exit(1);
}
getInput(stu);
if (*head != NULL) //不是空链表
{
temp = *head;
*head = stu;
stu->next = temp;
}
else
{
*head = stu;
stu->next = NULL;
}
}
int main()
{
struct Student *namelist = NULL; ////初始化一个指针,头指针,相当于定义了一个空的单链表
struct Student* stu;
int num;
printf("total num of stu:");
scanf_s("%d", &num);
printf("\n");
printf("enter info:\n");
for (int i = 0; i < num; i++)
{
head_add(&stu);
}
printf("finish entering!\n");
printf("begining to print\n");
printfInfo(&stu);
releaseMemory(&namelist);
return 0;
}
int main()
{
struct Student *namelist = NULL; ////初始化一个指针,头指针,相当于定义了一个空的单链表
struct Student* stu; // 指针 stu 未初始化
初始化一下就好了 struct Student* stu = NULL ;
|