链表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是否能够成功分配到内存; 无法删除链表中的项;