最近学的链表
写了个流程图
未命名文件 | ProcessOn免费在线作图,在线流程图,在线思维导图 |
#include<stdlib.h>
#include<stdio.h>
struct Stu
{
char name[20];//姓名
int num;//学号
struct Stu* next;
};
struct Stu* Create()
{
int count=0;//定义可以数 结点个数的变量
struct Stu* pre, * cur, * head = NULL;//定义结构体指针
pre = cur = (struct Stu*)malloc(sizeof(struct Stu));//分配内存
scanf_s("%s", &cur->name,20);//输入姓名学号,
//创建链表时用scanf char类型就会这样报错 写入某位置时发生访问冲突
//------------------(CSDN里查到)所以最重要的是要在scanf函参末尾加一个限制数字
scanf_s("%d",&cur->num);
while (cur->num!=0)//如果学号为0
{
count++;//结点多了一个
if (count == 1)//如果结点为一个
{
cur->next = NULL;//让当前结点的后继指针指向空
head = cur;//让头指针指向当前结点
}
else
{
cur->next = NULL;//让当前结点的后继指针指向空
pre->next = cur;//让前结点的后继指针指向当前指针
}
pre = cur;//把当前结点设为前结点,这样可以空出当前结点,并给新的“当前结点”分配内存
cur = (struct Stu*)malloc(sizeof(struct Stu));
scanf_s("%s", &cur->name,20);
scanf_s("%d", &cur->num);
}
free(cur);//释放内存
return head;//返回头指针(头指针指向首结点),即首结点地址
}
void print(struct Stu* head)
{
struct Stu* temp;//定义临时指针
temp = head;//把首结点地址赋给temp
while (temp != NULL)//如果没到末尾
{
printf("%s %d ",temp->name,temp->num);
temp = temp->next;//遍历结点,即,把下一个结点的地址赋给这个结点指针
}
}
int main()
{
struct Stu* head;
head = Create();
print(head);
}