#include <iostream>
using namespace std;
class my_stack
{
private:
int * data;
int size;
int top;
public:
my_stack(){}
my_stack(int size):size(size),top(-1)
{
data = new int[size];
}
~my_stack(){}
my_stack & operator=(const my_stack &other)
{
if(this!=&other)
{
this->data = other.data;
}
return *this;
}
void push(int value)
{
if(top>=size-1)
{
cout<<"栈满"<<endl;
}
this->top++;
data[top] = value;
}
void pop()
{
if(top==-1)
{
cout<<"栈空"<<endl;
}
cout<<"删除栈顶元素:"<<this->data[top]<<endl;
this->top--;
}
void get_top()
{
cout<<"此时的栈顶元素:"<<this->data[top]<<endl;
}
bool empty()const
{
return top+1;
}
int get_size()//返回元素数
{
return this->top+1;
}
void swap(my_stack & other)
{
int * temp;
temp = data;
data = other.data;
other.data = temp;
}
};
int main()
{
my_stack s1(10);
cout<<"容纳的元素数:"<<s1.get_size()<<endl;
s1.push(1);
s1.push(9);
cout<<"容纳的元素数:"<<s1.get_size()<<endl;
s1.get_top();//9
s1.pop();
s1.get_top();//1
s1.pop();
if(s1.empty()){
cout<<"栈不为空"<<endl;
}else{
cout<<"栈为空"<<endl;
}
s1.push(10);
s1.push(14);
s1.push(8);
s1.get_top();
cout<<"容纳的元素数:"<<s1.get_size()<<endl;
my_stack s2(10);
s2.push(999);
s2.swap(s1);
s2.get_top();
return 0;
}
9.25C++(day6)
最新推荐文章于 2024-09-26 09:13:29 发布