//数据类型
struct date
{
int year;
int month;
int day;
};
typedef struct gamemessage
{
int ID;
char name[20];
struct date issuingdate;
}GM;
//链表结点类型
struct node {
GM data; //链表节点存储的数据
struct node* pnext; //保存
};
//创建一个链表结点
struct node* createnode(GM* pdata)
{
struct node* pnew=malloc(sizeof(struct node));
if (pnew == NULL) //如果动态申请内存失败
return NULL;
pnew->pnext = NULL;
strcpy(pnew->data.name, pdata->name);
pnew->data.ID = pdata->ID;
pnew->data.issuingdate.year = pdata->issuingdate.year;
pnew->data.issuingdate.month = pdata->issuingdate.month;
pnew->data.issuingdate.day = pdata->issuingdate.day;
return pnew;
}
//添加一个结点到末尾
void appendnode(struct node** root, GM* pdata) {
if (root == NULL)return;
if (*root == NULL) {//传进来一个空链表
*root = createnode(pdata);
return;
}
struct node* ptemp = *root;
//让ptemp指向链表最后一个结点
while (ptemp->pnext)
ptemp = ptemp->pnext;
//把新结点添加到ptemp后面
ptemp->pnext = createnode(pdata);
}
声明过数据类型和链表结点类型后使用创建链表节点和添加结点到末尾的函数进行对链表的增加;
添加结点到链表末尾的函数可以使用二级指针:
void appendnode(struct node** root, GM* pdata) {
if (root == NULL)return;
if (*root == NULL) {//传进来一个空链表
*root = createnode(pdata);
return;
}
struct node* ptemp = *root;
//让ptemp指向链表最后一个结点
while (ptemp->pnext)
ptemp = ptemp->pnext;
//把新结点添加到ptemp后面
ptemp->pnext = createnode(pdata);
}
我们的单链表采用的是无头链表的方法,所以在头结点中也会有数据存储,所以我们可以使用二级指针来判断链表是否存在;二级指针的本质上就是链表的地址。
在函数运行时,我们首先要遍历链表至链表末尾,然后把新结点添加至链表末尾,添加新结点我们就调用createnode函数即可。