利用单链表实现简单的信息录入和打印功能

利用单链表实现简单的信息录入和打印功能,第1张

#define LEN sizeof(node)
struct student{
	char name[20];
	int age;
	float score;
};


typedef struct Node
{  
	//int data;
	struct student data;
	struct Node * next;
}node; //创建结点
//创建链表---> 创建表头--->就是创建结构体变量
//有头链表  链表表头不存放数据
//无头链表  链表表头存放数据

node * list = NULL;
node * createHead(){
	//结构体指针变成结构体变量---->通过动态内存申请
	node * headnode = (node *)malloc(LEN);
	//变量使用原则 --->使用前必须初始化
	headnode->next = NULL;
	return headnode;
}


//创建结点--->把用户的数据变成结构体变量的
node * createNode(struct student data){
	node * newnode = (node *)malloc(LEN);
	newnode->data = data;
	newnode->next = NULL;
	return newnode;
}

//插入结点 
void insertNode(node *headnode, struct student data){
	node * newnode = createNode(data);
	newnode->next = headnode->next;
	headnode->next = newnode;
}

//打印结点
void printf_list(node * headnode){
	node * pMove = headnode->next;
	printf("姓名\t年龄\t编号\n");
	while (pMove != NULL)
	{
		printf("%s\t%d\t%.1f\n", pMove->data.name, pMove->data.age,pMove->data.score);
		pMove = pMove->next;
	}
	putchar('\n');
}

void makeMenu(){
	printf("1.录入信息\n");
	printf("2.打印信息\n");
}
void keyDown(){
	int choice = 0;
	scanf("%d", &choice);
	struct student tempData;
	switch (choice)
	{
	case 1:
		printf("请输入name ,age ,score:");
		scanf("%s%d%f", tempData.name,&tempData.age,&tempData.score);
		insertNode(list, tempData);
		break;
	case 2:
		printf_list(list);
		break;
	default:
		printf("输入错误\n");
		break;
	}
}

int main(){
    list = createHead();
	while (1){
		makeMenu();
		keyDown();

	}
	return  0;
}

实现效果如下如图所示:

1.录入信息效果如下:

 2.打印效果如下:

 上面单链表创建采用的是  有表头 头插法  的形式进行创建.

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/580170.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-11
下一篇2022-04-11

发表评论

登录后才能评论

评论列表(0条)

    保存