84.链表C代码实现

链表C代码实现

#include <stdio.h>
#include <string.h>
#define 	NAME_SIZE 20//人名字符大小
typedef struct peoplecard
{
	char name[NAME_SIZE];
	int age;
	peoplecard* next;//指向下一个结构体的指针
}char* manage_gets(char str[],int len_limt);

int main(void)
{
	people_card*  head;
	people_card*  prev;
	people_card*  current;
	char name[NAME_SIZE];

printf()

while( manage_gets(name, NAME_SIZE)!= NULL  && name[0]!=’\0)
{
	current = (people_card*)malloc(sizeof(people_card));
	if(NULL==head)
	{
		head = current;
	}
	else
	{
		prev->next = current;
	}
	current->next = NULL;
	strcpy(current->name,name);
	puts(“Enter your age <0-200>:);
	scanf(%d”,& peol[i++].age);
	while(getchar()!=’\n’)
	{
		continue;
	}

	puts(“Enter next people name(empty line to stop):);
	prev=current;//跟踪新分配的结构的上一个结构用,类似于中间变量的作用
				//prev和current本身并不在链表里
}
显示链表
if(NULL==head)
	{
		printf(“No data entered”);
	}
	else
	{
		printf(“Here is the people list”);
		current  = head;
		while(current ! = NULL)
		{
			printf(“people name:%s,age:%d”,current->name, current->age);
			current = current->next;
		}
		
	//完成任务,释放已分配的内存,重新从头开始指向
	current  = head;
	while(current ! = NULL)
	{
		head=current->next
		free(current);
		current = head;
	}
	printf(“end bye”);
	}

	return 0;
}

char* manage_gets(char str[],int len_limt)
{
	char* ret_val;
	char* find;
	ret_val = fgets(str,len_limt,stdin);
	if(ret_val)
	{
		find = strchr(str,’\0);
		if(find)
		{
			*find = ‘\0;
		}
		else
		{
			while(getchar()!=’\n’)
			{
				continue;
			}
		}
	}
	return ret_val;
}

在这里插入图片描述
在这里插入图片描述

manage_gets这个函数的目的就是为了获取名字的字符串,但是由于fgets系统函数获取到的字符的末尾添加的是“\n”不是“\0”,所以要将“\n”替换成“\0”,而且要照顾软件的边界条件。

如果使用current和prev和head觉的比较乱,可以使用a,b,c,d来操作

释放已经分配的内存

链表2需要改进的地方:

没有检查malloc是否能够成功分配到内存; 无法删除链表中的项;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiawucha159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值