单向链表的创建
前言:链表的创建就是创建一个个节点并给节点输入数据,最后将节点按照一定逻辑关系组织起来的过程。
一、算法描述
(1)步骤描述
1. 读取数据;2. 生成新节点;3. 将数据存入新节点;4. 将新节点插入链表中。
(2)N-S流程图
二、代码分析
#include <stdio.h>
#include <malloc.h>
#define LEN sizeof(struct stu) /*LEN为结构体stu的长度*/
struct stu{ //定义一个包含学号和成绩的结构体
int num; //数据域
float score; //数据域
struct stu *next;//指针域
};
//结构体构造函数
struct stu *creat(){
struct stu *head, *tail; //链表的头指针和尾指针
struct stu *p; //代表新产生的节点
int x; //控制输入
head = tail =NULL; //初始化
printf("Please input the student number:");
scanf("%d",&x);
while(x!=0){
p = (struct stu*) malloc(LEN); //开辟一个空间
p->num = x;
printf("Please input the student score:");
scanf("%f",&p->score);
if(head == NULL) //解决了情况1:构建的节点是头节点
head = p;
if(tail != NULL) //解决了情况2:构建的节点不是头节点
tail->next = p;
tail = p; //始终让tail指向最后一个节点
printf("Please input the student number:");
scanf("%d",&x);
}
if(tail !=NULL)
tail->next = NULL;
return head;
}
三、解题思想
1. 对于节点的创建采用了内存动态管理函数,自动分配空间,具体可查看内存动态管理——malloc函数、calloc函数和free函数;
2. 对于节点的插入有两种情况,情况1:这个结点是头结点,情况2:这个结点不是头结点
3. 链表中两个标志性指针head和tail要及时更新,确保head始终位于第一个节点,tail始终位与最后一个节点