##单链表
可以认为是结构体中的递归。
单链表是最简单的一种链表实现方式,它包含两个域,一个信息域和一个指针域:
真正的单链表它还需要一个头指针,用于存放指向链表第一个节点的地址(这样你才能知道到它):
举个例子(头插法):
#include <stdio.h>
#include <stdlib.h>
struct Date
{
int year;
int month;
int day;
};
struct Record
{
char name[10];
int age;
struct Date first;
struct Date second;
struct Record *next;
};
void getInput(struct Record *record);
void printRecord(struct Record *record);
void addRecord(struct Record **head);
void releaseRecord(struct Record *record);
void getInput(struct Record *record)
{
printf("请问姓名是:");
scanf("%s",record-> name);
printf("请问年龄是:");
scanf("%d",&record->age);
printf("请问是否接种过疫苗(Y/N):");
getchar();
if(getchar() != 'Y')
{
record->first.year = 0;
printf("请尽快接种疫苗!\n");
}
else
{
printf("请输入第一针疫苗接种的日期(yyyy-mm-dd)");
scanf("%d-%d-%d",&record->first.year, &record->first.month, &record->first.day);
printf("请问是否接种第二针疫苗(Y/N):");
getchar();
if(getchar() != 'Y')
{
record->second.year = 0;
printf("请尽快接种第二针疫苗!\n");
}
else
{
printf("请输入第二针疫苗接种的日期(yyyy-mm-dd)");
scanf("%d-%d-%d",&record->second.year, &record->second.month, &record->second.day);
}
}
printf("\n");
}
void printRecord(struct Record *head)
{
while(head != NULL)
{
printf("姓名:%s,年龄:%d\n",head ->name, head->age);
if(head->first.year == 0)
{
printf("未接种疫苗!\n");
}
else
{
printf("第一针疫苗接种日期:%d-%d-%d\n",head->first.year, head->first.month, head->first.day);
}
if(head->first.year != 0 && head->second.year == 0)
{
printf("未接种第二针疫苗!\n");
}
else
{
printf("第二针疫苗接种日期:%d-%d-%d\n",head->second.year, head->second.month, head->second.day);
}
head = head ->next;
}
}
void addRecord(struct Record **head)//**head是指向指针的指针。
{
struct Record *record, *temp;
record = (struct Record *)malloc(sizeof(struct Record));
if(record == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
getInput(record);
if(*head != NULL)
{
temp = *head;//*head是被**head所指向的指针。
*head = record;
record->next = temp;//把原*head中的值传给连接着的链表。
}
else
{
*head = record;
record ->next = NULL;
}
}
void releaseRecord(struct Record *head)
{
struct Record *temp;
while(head != NULL)
{
temp = head;
head = head ->next;
free(temp);
}
}
int main(void)
{
struct Record *head = NULL;
int ch;
while(1)
{
printf("请问是否需要录入(Y/N):");
do
{
ch = getchar();
}while(ch != 'Y'&& ch != 'N');
if(ch == 'Y')
{
addRecord(&head);
}
else
{
break;
}
}
printf("请问是否需要打印已录入的数据(Y/N):");
do
{
ch = getchar();
}while(ch != 'Y' && ch!= 'N');
if(ch == 'Y')
{
printRecord(head);
}
releaseRecord(head);
return 0;
}
运行结果如下: