可见:不带头指针的插入操作比较繁琐,尤其是尾插法,每次需要遍历链表找到尾节点,然后执行插入操作
typedef int DATA;
struct SNode
{
DATA data;
SNode *pNext;
};
SNode *g_pHead = NULL;
/* 不带头结点的尾插法和头插法 */
void AddHead(DATA d)
{
SNode *p = (SNode *)malloc(sizeof(SNode));
p->data = d;
p->pNext = g_pHead; //新节点的后继
g_pHead = p; //首结点
}
void AddTail(DATA d)
{
SNode *ptr = g_pHead;
SNode *p = (SNode *)malloc(sizeof(SNode));
p->data = d;
p->pNext = NULL;
if (!ptr) //第一次为空节点时
{
g_pHead = p;
return;
}
while (ptr->pNext) //循环查找尾节点,然后插入
{
ptr = ptr->pNext;
}
ptr->pNext = p;
}