链表的添加的具体方法如下:
先判断链表是否有节点,
若没有, 头指针指向新来的节点,尾指针指向新来的节点。
若有, 尾节点的下一个指向新来的节点,尾指针指向新来的节点。
cpp
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int id;
char* name;
struct node* pnext;
}list;
list* getnode(int id, char* name)
{
list* ptemp = malloc(sizeof(list));
ptemp->id = id;
ptemp->name = name;
ptemp->pnext = NULL;
return ptemp;
}
void addnode(list** pphead, list** ppend, list* pnode)
{
if (NULL == *pphead)
{
*pphead = pnode;
*ppend = pnode;
}
else
{
(*ppend)->pnext = pnode;
*ppend = pnode;
}
}
int main()
{
list* phead = NULL;
list* pend = NULL;
addnode(&phead, &pend, getnode(1, "aa"));
addnode(&phead, &pend, getnode(2, "bb"));
addnode(&phead, &pend, getnode(3, "cc"));
addnode(&phead, &pend, getnode(4, "dd"));
while (phead != NULL)
{
printf("%d %s\n", phead->id, phead->name);
phead = phead->pnext;
}
return 0;
}