单链表是一种链式存取的数据结构,用一组地址任意的存储单元存放线性表中的数据元素。链表中的数据是以结点来表示的,每个结点的构成:元素(数据元素的映象)+指针(指示后继元素存储位置),元素就是存储数据的存储单元,指针就是连接每个结点的地址数据。
单链表的基本操作有以下:
SListNode* BuySListNode(DataType x); //申请内存空间
void SListPushBack(SListNode** ppHead, DataType x); //后插
void SListPopBack(SListNode** ppHead); //后删
void SListPushFront(SListNode** ppHead, DataType x); //前插
SListNode* SListFind(SListNode* pHead, DataType x); //寻找指定数
void SListInsest(SListNode** ppHead, SListNode* pos, DataType x); //插入
void SListErase(SListNode** ppHead, SListNode* pos); //删除指定数
void SListPrint(SListNode* pHead); //打印单链表
void SListDestory(SListNode** ppHead); //销毁单链表
申请内存空间
SListNode * BuySListNode(DataType x)//开辟一个新的结点
{
SListNode* NewNode;
NewNode = (SListNode *)malloc(sizeof(SListNode));
NewNode->_data = x;
NewNode->_next = NULL;
if (NewNode == NULL)
{
printf("申请内存空间失败\n");
return NULL;
}
return NewNode;
}
后插
void SListPushBack(SListNode ** ppHead, DataType x)//后插
{
SListNode* NewNode = BuySListNode(x);
SListNode* cur = *ppHead;
if (NULL == *ppHead)
{
*ppHead = NewNode;
}
else
{
while (cur->_next)
{
cur = cur->_next;
}
cur->_next = NewNode;
}
}
后删
void SListPopBack(SListNode ** ppHead)//后删
{
SListNode*cur = *ppHead;
while (cur->_next)
{
cur = cur->_next;
}
free(cur);
}
头插
void SListPushFront(SListNode ** ppHead, DataType x)//头插
{
SListNode*NewNode = BuySListNode(x);
if (*ppHead == NULL)
{
*ppHead = NewNode;
}
else
{
NewNode->_next = *ppHead;
*ppHead = NewNode;
}
}
寻找指定数
SListNode * SListFind(SListNode * pHead, DataType x)//寻找指定数
{
SListNode*cur;
cur = pHead;
while (cur->_next)
{
if (cur->_data = x)
{
return cur;
}
cur = cur->_next;
}
return NULL;
}
在pos插入x
void SListInsest(SListNode ** ppHead, SListNode * pos, DataType x)//在pos插入x
{
SListNode*NewNode = BuySListNode(x);
SListNode*cur;
cur = *ppHead;
while (cur->_next)
{
if (cur->_next = pos)
{
cur->_next = NewNode;
NewNode->_next = pos;
}
printf("单链表中无该位置");
}
return NULL;
}
删除pos
void SListErase(SListNode ** ppHead, SListNode * pos)//删除pos
{
SListNode*cur;
cur = *ppHead;
while (cur->_next)
{
if (cur->_next = pos)
{
cur->_next = pos->_next;
free(pos);
}
cur = cur->_next;
}
return NULL;
}
打印单链表
void SListPrint(SListNode * pHead)//打印
{
SListNode*cur = pHead;
while (cur->_next)
{
printf("%d->", cur->_data);
cur = cur->_next;
}
printf("NULL\n");
}
销毁单链表
void SListDestory(SListNode ** ppHead)//销毁
{
SListNode*cur = *ppHead;
while (cur->_next)
{
free(cur);
cur = cur->_next;
}
free(*ppHead);
}