#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student
{
char name[20];
int age ;
struct Student* stu_Next;
};
int main(){
struct Student* pStuHand= NULL; //只保留下一条的数据
struct Student* pTemp = NULL;
struct Student* p = NULL;
char str[18] = { 0 };
//申请一个头,头中除了下一个链表地址,不存在其它内容
pStuHand = (struct Student*)malloc(sizeof(struct Student));
memset(pStuHand, 0, sizeof(struct Student));
pStuHand->stu_Next = NULL;
//写入内容
for (int i = 0;i < 100;i++)
{
//写入姓名
memset(&str, 0, sizeof(str));
sprintf_s(&str, sizeof(str), "%s%d", "小明", i);
pTemp = (struct Student*)malloc(sizeof(struct Student));
memset(pTemp, 0, sizeof(struct Student));
//设置申请临时结构内容
pTemp->age = i + 1;
strcpy_s(pTemp->name, sizeof(str), &str);
//新申请内容写入链表
p = pStuHand;
while (1)
{
if (p->stu_Next == NULL)
{
p->stu_Next = pTemp;
break;
}else
{
p = p->stu_Next;
}
}
}
//输出内容
pTemp = pStuHand->stu_Next;
while (1)
{
if (pTemp ==NULL)
{
break;
}
printf("姓名:%s,年龄:%d\n", pTemp->name, pTemp->age);
pTemp = pTemp->stu_Next;
}
//释放内存
pTemp = pStuHand->stu_Next;
while (1)
{
if (pTemp == NULL)
{
break;
}
p = pTemp->stu_Next;
free(pTemp);
pTemp = p;
}
free(pStuHand); //释放头
getchar();
return 0;
}
C语言单链表演示
最新推荐文章于 2024-09-16 08:54:02 发布