数据结构:栈的实现

本文详细介绍了 C++ 中栈的基本实现方式,包括构造、判断空栈、判断满栈、入栈、出栈、获取栈顶元素及弹出栈顶元素的操作。通过实例演示了如何使用数组来实现栈,并提供了相应的输入输出流程。

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



using namespace std;
class Stack
{
private:
int maxSize;
int top;
int theArray[100];


public:
Stack(int capacity)
{
maxSize = capacity;
top = -1;
int x;
cin>>x;
int i = 0;
while(x != 0)
{
theArray[++top] = x;
cin>>x;
}
}


bool isEmpty()
{
return top == -1;
}


bool isFull()
{
return top == maxSize - 1;
}


void push(int x)
{
if(isFull())
cout<<"push failed,the stack is full"<<endl;
else
{
theArray[++top] = x;
}
}


void pop()
{
if(isEmpty())
cout<<"pop failed,the stack is empty"<<endl;
else
{
top--;
}
}


int topAndPop()
{
if(isEmpty())
cout<<"top and pop failed,the stack is empty"<<endl;
else
{
return theArray[top - 1];
top--;
}
}


int Top()
{
if(isEmpty())
cout<<"top failed,the stack is empty"<<endl;
else
return theArray[top];
}


void outputStack()
{
if(isEmpty())
cout<<"output failed,the stack is empty"<<endl;
else
{
for(int i = 0;i <= top;i ++)
{
cout<<theArray[i]<<" ";
}
}
}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值