溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C語言數(shù)據(jù)結(jié)構(gòu) 單鏈表及其基本功能實(shí)現(xiàn)

發(fā)布時間:2020-06-24 19:32:21 來源:網(wǎng)絡(luò) 閱讀:208 作者:sonissa 欄目:編程語言

頭文件如下:

#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

具體功能實(shí)現(xiàn)如下:

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的前面進(jìn)行插入
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)//刪除某個值的所有節(jié)點(diǎn)
{
    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;
}
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI