版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40797414/article/details/82226989
#pragma once
typedef int DataType;
#include<stdio.h>
typedef struct Node//不带头结点的单链表
{
struct Node* _pNext;
DataType _data;
}Node,*PNode;
#include<stdio.h>
#include<assert.h>
#include<malloc.h>
void SListInit(PNode* pHead)
{
assert(pHead);
*pHead = NULL;
}
void SListPushBack(PNode* pHead, DataType data)//尾插结点
{
PNode pNewNode = NULL;
assert(pHead);
pNewNode = BuySListNode(data);
//空
if (NULL == *pHead)
*pHead = pNewNode;
else//非空
{
PNode pCur = *pHead;
while (pCur->_pNext)
pCur = pCur->_pNext;
pCur->_pNext = pNewNode;
}
}
void SListPopBack(PNode* pHead)
{
assert(pHead);
if (NULL == *pHead)
return;
else if (NULL == (*pHead)->_pNext)
{
free(*pHead);
*pHead = NULL;
}
else
{
PNode pCur = *pHead;
while (pCur->_pNext->_pNext)
pCur = pCur->_pNext;
free(pCur->_pNext);
pCur->_pNext = NULL;
}
}
void DListPushFront(PNode* pHead, DataType data)//头插
{
PNode pNewNode = NULL;
assert(pHead);
pNewNode = BuySListNode(data);
if (NULL == pNewNode)
return;
pNewNode->_pNext = *pHead;
*pHead = pNewNode;
}
void SListPopFront(PNode* pHead)//头删
{
PNode pDelNode = NULL;
assert(pHead);
if (NULL == *pHead)
return;
pDelNode = *pHead;
*pHead = pDelNode->_pNext;
free(pDelNode);
}
PNode SListFind(PNode pHead, DataType data)//查找一个结点
{
PNode pCur = pHead;
while (pCur)
{
if (data == pCur->_data)
return pCur;
pCur = pCur->_pNext;
}
return NULL;
}
void SListInsert(PNode* pHead, PNode pos, DataType data)
{
PNode pNewNode = NULL;
assert(pHead);
if (NULL == *pHead || NULL == pos)
{
return;
}
pNewNode = BuySListNode(data);
if (NULL == pNewNode)
return;
pNewNode->_pNext = pos->_pNext;
pos->_pNext = pNewNode;
}
void SListErase(PNode* pHead, PNode pos)//删除任意位置的元素
{
assert(pHead);
if (NULL == *pHeas || NULL == pos)
return;
if (pos == *pHead)
SListPopFront(pHead);
else
{
PNode pCur = *pHead;
while (pCur&&pCur->_pNext != pos)
pCur = pCur->_pNext;
if (pCur)
{
pCur->_pNext = pos->_pNext;
free(pos);
}
}
}
void SListDestory(PNode* pHead)
{
SListClear(pHead);
}
int SListSize(PNode pHead)//链表有效元素的个数
{
int count = 0;
PNode pCur = pHead;
while (pCur)
{
count++;
pCur = pCur->_pNext;
}
return count;
}
void SListClear(PNode* pHead)//清除链表
{
PNode pDelNode = NULL;
assert(pHead);
while (*pHead)
{
pDelNode = *pHead;
*pHead = pDelNode->_pNext;
free(pDelNode);
}
}
PNode BuySListNode(DataType data)//买一个结点
{
PNode pNewNode = (PNode)malloc(sizeof(Node));
{
if (NULL == pNewNode)
return NULL;
}
pNewNode->_pNext = NULL;
pNewNode->_data = data;
return pNewNode;
}
PNode SListBack(PNode pHead)//找链表中最后一个结点的位置
{
PNode pCur = pHead;
if (NULL == pHead)
return NULL;
while (pCur->_pNext)
pCur = pCur->_pNext;
return pCur;
}
void PrintList(PNode pHead)
{
PNode pCur = pHead;
while (pCur)
{
printf("%d---->", pCur->_data);
pCur = pCur->_pNext;
}
printf("NULL\n");
}