单链表:是一种链式存储的线性表,用一组任意的存储单元存放线性表的元素,称存储单元为一个节点。
单链表的结构:
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node* pNext;
}Node, *PNode, **PPNode;
单链表简单操作:
void InitList(PPNode pHead) // 初始化单链表
{
*pHead = NULL;
}
Node* BuyNode(DataType data) // 构建一个新节点
{
PNode _node = (PNode)malloc(sizeof(Node));
if (NULL == _node)
exit(-1);
_node->data = data;
_node->pNext = NULL;
return _node;
}
void PushBack(PPNode pHead, DataType data) // 在单链表的尾部插入一个节点
{
assert(pHead);
if (NULL == *pHead)
{
*pHead = BuyNode(data);
}
else
{
PNode pnode = *pHead;
while (pnode->pNext)
{
pnode = pnode->pNext;
}
pnode->pNext = BuyNode(data);
}
}
void PopBack(PPNode pHead) // 删除单链表的最后一个节点
{
assert(pHead);
if (NULL != *pHead)
{
PNode pnode = *pHead;
while (pnode->_pNext->pNext)
{
pnode = pnode->pNext;
}
free(pnode->pNext);
pnode->pNext = NULL;
}
}
void PushFront(PPNode pHead, DataType data) // 在单链表的头部插入值为data的结点
{
assert(pHead);
if (NULL == *pHead)
{
*pHead = BuyNode(data);
}
else
{
PNode pnode = BuyNode(data);
pnode->pNext = *pHead;
*pHead = pnode;
}
}
void PopFront(PPNode pHead) // 删除单链表的第一个结点
{
assert(pHead);
if (NULL == *pHead)
{
return;
}
else
{
PNode pnode = (*pHead)->pNext;
free(*pHead);
*pHead = pnode;
}
}
Node* Find(PNode pHead, DataType data) // 在单链表中查找值为data的结点,找到了返回该结点的地址,否则返回NULL
{
if (NULL != pHead)
{
PNode pnode = pHead;
while (pnode)
{
if (pnode->data == data)
return pnode;
pnode = pnode->pNext;
}
}
return NULL;
}
void Insert(PPNode pHead,PNode pos, DataType data) // 在单链表pos位置后插入值为data的结点
{
assert(pHead);
PNode pnode = *pHead;
PNode _pnode = NULL;
if (NULL == *pHead || NULL == pos)
return;
while (pnode != pos)
pnode = pnode->pNext;
_pnode = BuyNode(data);
_pnode->_pNext = pnode->pNext;
pnode->_pNext = pnode;
}
void Erase(PPNode pHead, PNode pos) // 在单链表中删除位置为pos的结点
{
assert(pHead);
PNode pnode = *pHead;
if (NULL == *pHead || NULL == pos)
return;
while (pnode != pos)
pnode = pnode->pNext;
PNode pnode = pnode->pNext->pNext;
pnode->data = pnode->pNext->data;
free(pnode->pNext);
pnode->_pNext = pnode;
}
void Remove(PPNode pHead, DataType data) // 移除单链表中第一个值为data的结点
{
assert(pHead);
Erase(pHead, Find(*pHead, data));
}
void RemoveAll(PPNode pHead, DataType data) // 移除单链表中所有值为data的结点
{
assert(pHead);
PNode pnode = NULL;
if (NULL == *pHead)
return;
pnode = *pHead;
while (pnode->pNext)
{
if (pnode->data == data)
{
Erase(&pnode, pnode);
}
else
{
pnode = pnode->pNext;
}
}
}
size_t Size(PNode pHead) // 获取单链表总结点的总个数
{
size_t count = 0;
if (NULL == pHead)
return 0;
while (pHead)
{
++count;
pHead = pHead->pNext;
}
return count;
}
int Empty(PNode pHead) // 判断链表是否为空
{
if (NULL == pHead)
return NULL;
}
PNode Back(PNode pHead) // 返回单链表的最后一个结点的位置
{
if (NULL == pHead)
return NULL;
while (pHead->pNext)
pHead = pHead->pNext;
return pHead;
}
PNode Front(PNode pHead) // 返回单链表的第一个结点的位置
{
if (NULL == pHead)
return NULL;
return pHead;
}
void PrintList(PNode pHead) // 逆向打印单链表
{
if (NULL != pHead)
{
if (pHead->pNext != NULL)
{
PrintList(pHead->pNext);
}
}
printf("%d ",pHead->data);
}