温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言数据结构 单链表及其基本功能实现

发布时间:2020-06-24 19:32:21 来源:网络 阅读:196 作者: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

具体功能实现如下:

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;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI