C++实现一个简单的栈

该代码定义了一个C++类`stack`,用于模拟栈数据结构。类中包含push方法添加元素到栈顶,pop方法移除并返回栈顶元素,以及top方法查看栈顶元素但不删除。在主函数中,创建栈对象`s`,并进行入栈、查看栈顶及出栈操作。

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

#include<iostream>
using namespace std;

class stack{
	private:
		int s[1010];
		int top_index=-1;
	public:
		void push(int x){
			top_index+=1;
			s[top_index]=x;
		}
		void pop(){
			if(top_index>=0){
				cout<<s[top_index]<<endl;
				top_index-=1;
			}
			else{
				cout<<"error"<<endl;
			}
		}
		void top(){
			if(top_index>=0){
				cout<<s[top_index]<<endl;
			}
			else{
				cout<<"error"<<endl;
			}
		}
};

int main(){
	stack s;
	// 将1入栈 
	s.push(1);
	// 将2入栈 
	s.push(2);
	// 输出栈顶 
	s.top();
	// 输出栈顶,并让栈顶元素出栈 
	s.pop();
	// 输出栈顶 
	s.top();
	return 0;
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值