使用C++实现单链表的基本操作

介绍

本文介绍了使用C++实现单链表的基本操作,包括尾部插入、尾部删除、头部插入和头部删除。单链表是一种基本的数据结构,掌握了这些基本操作对于初学者来说非常重要。

代码实现

 
#include<iostream>
using namespace std;

// 定义单链表节点结构体
typedef int SLTDateType;
typedef struct SListNode
{
    SLTDateType data;
    SListNode* next;
}SListNode;

// 申请单链表节点
SListNode* BuySListNode(SLTDateType x)
{
    SListNode* newnode = new SListNode;
    if (newnode == NULL)
    {
        cout << "申请失败\n";
        exit(-1);
    }
    newnode->data = x;
    newnode->next = NULL;
    return newnode;
}

// 尾部插入节点
void SLTPushBack(SListNode** phead, SLTDateType x)
{
    SListNode* newNode = BuySListNode(x);

    if (*phead == NULL)
    {
        *phead = newNode;
    }
    else
    {
        SListNode* tail = *phead;
        while (tail->next != NULL)
        {
            tail = tail->next;
        }
        tail->next = newNode;
    }
}

// 尾部删除节点
void SLTPopBack(SListNode** phead)
{
    if (*phead == NULL)
    {
        return;
    }
    else if ((*phead)->next == NULL)
    {
        free(*phead);
        *phead = NULL;
    }
    else {
        SListNode* prev = NULL;
        SListNode* tail = *phead;
        while (tail->next != NULL)
        {
            prev = tail;
            tail = tail->next;
        }
        delete tail;
        tail = NULL;
        prev->next = NULL;
    }
}

// 头部插入节点
void SLTPushFront(SListNode** phead, SLTDateType x)
{
    SListNode* newNode = BuySListNode(x);
    newNode->next = *phead;
    *phead = newNode;
}

// 头部删除节点
void SLTPopFront(SListNode** phead)
{
    if (*phead == NULL)
    {
        return;
    }
    else
    {
        SListNode* next = (*phead)->next;
        delete *phead;
        *phead = next;
    }
}

// 打印链表
void SLTPrint(SListNode* phead)
{
    SListNode* cur = phead;
    while (cur != NULL)
    {
        printf("%d", cur->data);
        if (cur->next != NULL)
        {
            printf("  ->  ");
        }
        cur = cur->next;
    }
}

int main()
{
    SListNode* head = NULL;
    SLTPushBack(&head, 1);
    SLTPushBack(&head, 2);
    SLTPushBack(&head, 3);
    SLTPushBack(&head, 4);
    SLTPushFront(&head, 10);
    SLTPushFront(&head, 20);
    SLTPopFront(&head);
    SLTPushFront(&head, 30);
    SLTPopFront(&head);
    SLTPopFront(&head);
    SLTPopFront(&head);
    SLTPopFront(&head);
    SLTPopFront(&head);
    SLTPopFront(&head);
    SLTPopFront(&head);
    SLTPrint(head);
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值