用vector:
#include <vector>
#include <iostream>
using namespace std;
class Mystack{
public:
Mystack(){ //写一个栈的构造函数,vec+idx来标记
top_idx=0;
data.push_back(-1);
}
bool empty(){
if(data[top_idx]==-1){
return true;
}
return false;
}
void push(int x){ //填入元素,栈顶坐标后移
data.push_back(x);
top_idx++;
}
void pop(){ //弹出元素,栈顶坐标前移
data.pop_back();
top_idx--;
}
int top(){ //取栈顶元素
return data[top_idx];
}
private:
int top_idx ;
vector<int> data;
};
int main(){
Mystack s;
cout<<"-------1 represent the the stack is empty-------"<<endl;
cout<<s.empty()<<endl;
vector<int> vec{1,23,4,5,6};
for(int i=0;i<vec.size();++i){
s.push(vec[i]);
}
cout<<"-------from the top of the stack-------"<<endl;
while(!s.empty()){
cout<<s.top()<<endl;
s.pop();
}
system("pause");
return 0;
}
不用vector,用数组
#include <iostream>
using namespace std;
struct Mystack{
void InitStack(){
TOP = -1;
}
void clear(){
TOP = -1;
}
int size1() {
return TOP+1;
}
bool empty(){
if(TOP == -1) return true;
else return false;
}
//栈满不能push
void push(int x) {
//if()
st[++TOP] = x;
}
void pop(){
TOP--;
}
//栈空取顶报错
int top(){
//if()
return st[TOP];
}
private:
int st[10];
int TOP ;
};
int main()
{
Mystack stc;
stc.InitStack();
//int m;
for(int i=0; i<10 ;i++)
{
stc.push(i);
//cin >> m;
}
cout <<stc.top()<<endl;
cout << stc.size1();
}