数据结构与算法之—顺序栈c++面向对象实现

本文介绍了如何使用C++面向对象编程实现顺序栈。详细展示了构造函数、析构函数、判断栈空、栈满、压栈、弹栈、获取栈顶元素等操作的代码实现,并通过一个实例演示了进栈和出栈的过程。

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

#include<iostream>
using namespace std;


template<class T>
class my_stack
{
public:
my_stack(int n = 10);
~my_stack();
bool empty()const;
bool full()const;
bool push(const T& element);
bool pop();
bool get_top(T& top)const;


private:
T* a;
int m_size;
int m_max_size;
};


template<class T> 
my_stack<T>::my_stack(int n)
{
m_size = 0;
a = new T[n];
if(a == NULL)
{
m_max_size = 0;
}
else
{
m_max_size = n;
}
}


template<class T>
my_stack<T>::~my_stack()
{
delete []a;
}


template<class T>
bool my_stack<T>::empty()const
{
return m_size == 0 ? true : false;
}


template<class T>
bool my_stack<T>::full()const
{
return m_size == m_max_size ? true : false;
}


template<class T>
bool my_stack<T>::push(const T& element)
{
if(full())
{
return  false;
}
else
{
a[m_size++] = element;
return true;
}
}


template<class T>
bool my_stack<T>::get_top(T& top)const
{
if(empty())
{
return  false;
}
else
{
top = a[m_size-1];
return true;
}
}


template<class T>
bool my_stack<T>::pop()
{
if(empty())
{
return false;
}
else
{
m_size--;
return true;
}
}




int main()
{
my_stack<int> s(20);
    //进栈
cout<<"进栈"<<endl;
for(int i = 0; i < 20; i++)
{
s.push(i);
int t = -1;
if(s.get_top(t))
{
cout<<t<<' ';
}
}


cout<<endl;
cout<<"出栈"<<endl;
    //出栈
for(int j = 0; j < 20; j++)
{
int t = -1;
if(s.get_top(t))
{
cout<<t<<' ';
}
if(s.pop())
{

}
}


return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值