Node Pnode;
void SListInit(SList* s)
{
s->_pHead = NULL;
}
//构建一个结点
PNode BuySListNode(SDataType _data)
{
PNode node = (PNode)malloc(sizeof(Node));
if (node)
{
node->_data = _data;
node->_PNext = NULL;
}
return node;
}
/*
尾插,首先要创建一个新节点,然后判断链表当前是否有节点,若没有,则直接让第一个节点指向新节点,
若有,找到最后一个节点,让他指向新节点
*/
void SListPushBack(SList* s, SDataType data)
{
//找链表最后一个节点
PNode pNewNode = BuySListNode(data);
if (s->_pHead == NULL) {//链表没有节点的情况
s->_pHead = pNewNode;
}
else {
PNode pCur = s->_pHead;
while (pCur->_PNext) {
pCur = pCur->_PNext;
}
//让最后一个节点指向新节点
pCur->_PNext = pNewNode;
}
}
/*查找某个特征的节点*/
PNode SListFind(SList* s, SDataType data)
{
PNode pCur = s->_pHead;
while (pCur) {
if (pCur->_data == data) {
return pCur;
}
pCur = pCur->_PNext;
}
return NULL;
}
/*
删除给定pos位置的节点
*/
void SListErase(SList* s, PNode pos)
{
if (pos == NULL || s->_pHead == NULL) {
return;
}
if (pos== s->_pHead) {
s->_pHead = pos->_PNext;
}
else {
PNode pPrePos = s->_pHead;
while (pPrePos&&pPrePos->_PNext != pos) {
pPrePos = pPrePos->_PNext;
}
pPrePos->_PNext = pos->_PNext;
}
free(pos);
}
//获取链表有效节点的个数
int SListSize(SList* s)
{
int count = 0;
PNode pCur = s->_pHead;
while (pCur) {
count++;
pCur = pCur->_PNext;
}
return count;
}
//检测链表是否为空
int SListEmpty(SList* s)
{
if (s->_pHead == NULL)
{
return -1;
}
return 0;
}
//清空链表
void SListClear(SList* s)
{
if (s->_pHead == NULL) {
return;
}
PNode pCur = s->_pHead;
while (pCur->_PNext) { //循环清空链表中的节点
PNode Tmp = pCur->_PNext;
free(pCur);
pCur = Tmp;
}
if (pCur) { //清空最后一个节点
free(pCur);
pCur = NULL;
}
}
//销毁链表
void SListDestroy(SList* s)
{
if (s->_pHead == NULL) {
free(s->_pHead);
return;
}
while (s->_pHead) {
PNode Tmp = s->_pHead->_PNext;
free(s->_pHead);
s->_pHead = Tmp;
}
}
//打印链表
void SListPrint(SList* s)
{
PNode pCur = s->_pHead;
while (pCur) {
printf("%d--->", pCur->_data);
pCur = pCur->_PNext;
}
printf("\n");
}
/**********************Tests**************************************
void main()
{
SList s;
SListInit(&s);
SListPushBack(&s, 1);
SListPushBack(&s, 2);
SListPushBack(&s, 3);
printf("size=%d\n", SListSize(&s));
SListPrint(&s);
SListInsert(SListFind(&s, 2), 0);
SListPrint(&s);
SListRemove(&s, 2);
SListPrint(&s);
system("pause");
return;
}
*****************************************************************/