结构体的创建
typedef int DataType;
typedef struct Node
{
struct Node* _pNext;
DataType _data;
}Node, *PNode;
创建一个新节点
PNode BuyNode(DataType data)
{
PNode pnew = NULL;
pnew = (PNode)malloc(sizeof(Node));
if (NULL == pnew)
{
printf("malloc开辟空间失败!!");
}
else
{
pnew->_data = data;
pnew->_pNext = NULL;
}
return pnew;
}
链表的插入
1.在链表的尾部插入一个新节点
void SListPushBack(PNode* pHead, DataType data)
{
if (NULL == *pHead)
{
*pHead = BuyNode(data);
}
else
{
PNode pcur = *pHead;
while (pcur->_pNext)
{
pcur = pcur->_pNext;
}
pcur->_pNext = BuyNode(data);
}
}
2.在链表的头部插入一个新节点
void SListPushFront(PNode* pHead, DataType data)
{
assert(pHead);
if (!(*pHead))
{
*pHead = BuyNode(data);
}
else
{
PNode pcur = *pHead;
*pHead = BuyNode(data);
(*pHead)->_pNext = pcur;
}
}
3.在链表的指定位置后插入一个新节点
void SListInsert(PNode* pHead, PNode pos, DataType data)
{
assert(pHead);
assert(pos);
PNode pcur = pos->_pNext;
pos->_pNext = BuyNode(data);
free(pcur);
pcur = NULL;
}
链表的删除
1.在链表的尾部删除一个节点
void SListPopBack(PNode* pHead)
{
assert(pHead);
if (NULL == *pHead)
{
return;
}
else if (!(*pHead)->_data)
{
PNode pcur = *pHead;
pHead = NULL;
free(pcur);
pcur = NULL;
}
else
{
PNode pcur = *pHead;
while (pcur->_pNext)
{
pcur = pcur->_pNext;
}
PNode pret = pcur;
pcur = NULL;
free(pret);
pret = NULL;
}
}
2.在链表的头部删除一个节点
void SListPopFront(PNode* pHead)
{
if (!(*pHead))
{
return;
}
else if(!((*pHead)->_pNext))
{
PNode pcur = *pHead;
*pHead = NULL;
free(pcur);
pcur = NULL;
}
else
{
PNode pcur = (*pHead)->_pNext;
PNode pret = *pHead;
*pHead = pcur;
free(pret);
pret = NULL;
}
}
3.删除指定位置的节点
void SListErase(PNode* pHead, PNode pos)
{
assert(pHead);
assert(pos);
if (*pHead == pos)
{
*pHead = pos->_pNext;
}
else
{
PNode pcur = *pHead;
PNode pret = (*pHead)->_pNext;
while (pret != pos)
{
pcur = pcur->_pNext;
pret = pret->_pNext;
}
pcur->_pNext = pos->_pNext;
}
free(pos);
}
求链表中节点的个数
int SListSize(PNode pHead)
{
int count = 0;
PNode pcur = pHead;
while (pcur)
{
count++;
pcur = pcur->_pNext;
}
return count;
}
获取链表尾部的地址
PNode SListBack(PNode pHead)
{
PNode pcur = NULL;
pcur = pHead;
while (pcur&&pcur->_pNext)
{
pcur = pcur->_pNext;
}
return pcur;
}
销毁链表
void SListDestroy(PNode* pHead)
{
assert(pHead);
PNode pcur = *pHead;
while (pcur)
{
PNode pret = NULL;
pret = pcur;
pcur = pcur->_pNext;
free(pret);
}
*pHead = NULL;
}