栈的创建、入栈、出栈、统计长度

本文介绍了一种使用C++中的链表来实现栈的方法。通过定义节点结构体和链表栈结构体,实现了栈的基本操作:创建空栈、元素入栈及元素出栈,并附带了一个简单的示例程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++实现,采用链表存储,因为顺序存储较为简单,不再重复叙述。

#include <iostream>

using namespace std;

struct node         //栈的节点
{
    int data;
    struct node *next;
};

struct linkStack
{
    struct node *top;      //指向栈顶节点
    int lengthStack;      //栈长度
};

//创建一个空栈
void create(struct linkStack *S)
{
    S->top = NULL;
    S->lengthStack = 0;
}

//入栈数据num
void stackInsert(struct linkStack *S, int num)
{
    struct node *p = new node;
    p->data = num;
    if(S->top == NULL)      //当栈为空时
        S->top = p;
    else        //当栈不为空时
    {
        p->next = S->top;
        S->top = p;
    }
    S->lengthStack++;
}

//出栈并打印出栈的数据
void stackPop(struct linkStack *S)
{
    struct node *temp;
    if(S->top != NULL)
    {
        temp = S->top;
        S->top = S->top->next;
        cout<<temp->data<<endl;
        delete(temp);
        S->lengthStack--;
    }
}

int main()
{
    linkStack S;
    create(&S);
    /********入栈*************/
    stackInsert(&S, 1);
    stackInsert(&S, 2);
    stackInsert(&S, 3);
    stackInsert(&S, 4);
    /********出栈*************/
    stackPop(&S);
    stackPop(&S);
    stackPop(&S);
    stackPop(&S);
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值