带头节点的单链表的基本操作 --- (创建,头插,头删,尾插,尾删)

上一篇博客讲述了不带头节点的单链表,这篇博客就是有关带头结点单链表的基本函数

结构体:

typedef int DataType;

typedef struct SHListNode
{
    struct SHListNode* _pNext;
    DataType _data;
}SHListNode,Node;

基本函数:

SHListNode* BuySHListNode(DataType data)//创建一个节点
{
    SHListNode* pNewNode = (SHListNode*)malloc(sizeof(SHListNode));
    if (NULL == pNewNode)
    {
        assert(0);
        return NULL;
    }
    pNewNode->_data = data;
    pNewNode->_pNext = NULL;
    return pNewNode;
}

void SHListInit(SHListNode** pHead)//头节点
{
    assert(pHead);
    *pHead = BuySHListNode(0);

}

void SHListPushBack(SHListNode* pHead, DataType data)//尾插
{
    Node* pTailNode = pHead;
    assert(pHead);
    while (pTailNode->_pNext)
    {
        pTailNode = pTailNode->_pNext;
    }
    pTailNode->_pNext = BuySHListNode(data);

}


//空链表:pHead->头节点:->NULL
//非空链表
void SHListPopBack(SHListNode* pHead)//尾删
{
    Node* pTailNode = pHead;
    Node* pre = NULL;
    assert(pHead);
    if (NULL == pHead->_pNext)
    {
        return 0;
    }
    while (pTailNode->_pNext)
    {
        pre = pTailNode;
        pTailNode = pTailNode->_pNext;
    }
    pre->_pNext = NULL;
    free(pTailNode);
    pTailNode = NULL;
}


void SHListPushFront(SHListNode* pHead, DataType data)//头插
{
    Node* pNewNode = NULL;
    assert(pHead);
    pNewNode = BuySHListNode(data);
    if (pNewNode != NULL)
    {
        pNewNode->_pNext = pHead->_pNext;
        pHead->_pNext = pNewNode;
    }
}

void SHListPopFront(SHListNode* pHead)//头删
{
    Node* pDelNode = NULL;
    assert(pHead);
    if (NULL == pHead->_pNext)
    {
        return;
    }
    pDelNode = pHead->_pNext;
    pHead->_pNext = pDelNode->_pNext;
    free(pDelNode);
    pDelNode = NULL;
}
以上是有关带头节点单链表的基本函数,希望对你有所帮助,如果有问题的可以留言,大家交流交流
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值