C語言數據結構 單鏈表及其基本功能實現

頭文件以下:ide

#ifndef _SLIST_H_
#define _SLIST_H_

typedef int SLTDataType;
typedef struct SListNode
{
    SLTDataType data;
    struct SListNode* next;
}SListNode;

void SListInit(SListNode** phead);
void SListDestory(SListNode* phead);
SListNode* BuySListNode(SLTDataType x);
void SListPushFront(SListNode** phead, SLTDataType x);
void SListPopFront(SListNode** phead);
SListNode* SListFind(SListNode* phead, SLTDataType x);

void SListInsertAfter(SListNode* pos, SLTDataType x);

void SListEraseAfter(SListNode* pos);
void SListRemoveA(SListNode** phead, SLTDataType x);
void SListPrint(SListNode* phead);
void TestSList();

#endif

具體功能實現以下:code

void SListInit(SListNode** pphead)
{
    *pphead = NULL;
}

SListNode* BuySListNode(SLTDataType x)
{
    SListNode* res = (SListNode*)malloc(sizeof(SListNode));
    res->data = x;
    res->next = NULL;
    return res;
}
void SListPushFront(SListNode** pphead, SLTDataType x)
{
    SListNode* tmp = BuySListNode(x);
    tmp->next = *pphead;
    *pphead = tmp;
}
void SListPopFront(SListNode** pphead)
{
    SListNode* tmp = (*pphead)->next;
    free(*pphead);
    *pphead = tmp;
}
void SListInsertAfter(SListNode* pos, SLTDataType x)//後插
{
    SListNode* tmp = BuySListNode(x);
    tmp->next = pos->next;
    pos->next = tmp;
}
// 在pos的前面進行插入
void SListEraseAfter(SListNode* pos)//後刪
{
    SListNode* tmp = pos->next;
    if (tmp == NULL)
    {
        return;
    }
    pos->next = tmp->next;
    free(tmp);
}

SListNode* SListFind(SListNode* phead, SLTDataType x)//查找
{
    SListNode* tmp;
    for (tmp = phead; tmp; tmp = tmp->next)
    {
        if (tmp->data == x)
        {
            return tmp;
        }
    }
    return NULL;
}

void SListRemoveA(SListNode** pphead, SLTDataType x)//刪除某個值的全部節點
{
    SListNode* tmp;
    while(*pphead&&(*pphead)->data==x)
    {
        SListPopFront(pphead);
    }
    for (tmp = *pphead;tmp&&tmp->next; )
    {       
        if (tmp->next->data==x)
        {
            SListEraseAfter(tmp);
        }
        else
        {
            tmp = tmp->next;
        }
    }
}

void SListPrint(SListNode* phead)
{
    SListNode* tmp;
    for (tmp = phead; tmp; tmp = tmp->next)
    {
        printf("%d->", tmp->data);
    }
    if (tmp == NULL)
    {
        printf("NULL");
    }
    printf("\n");
}

void SListDestory(SListNode* phead)//方法一:不斷後刪(此處),方法二:不斷頭刪
{
    while (phead->next)
    {
        SListEraseAfter(phead);
    }
    free(phead);
    //phead = NULL;
}
相關文章
相關標籤/搜索