#include <vector>
using namespace std;
class Stack {
public:
Stack() {} //初始化栈
void push(int x) { //压栈
data.push_back(x);
return;
}
void pop() { //出栈
if(empty()) return; //出栈之前先判空
data.pop_back();
}
bool empty() { //判空
return data.size() == 0; //判断数组中元素数量是否为0即可
}
int size() { //返回栈内元素数量
return data.size();
}
void output() { //输出栈中所有元素
cout << "======" << endl;
for(int i = data.size()-1; i >= 0; i--) { //逆序地遍历vector中的每一个元素
cout << data[i] <<endl;
}
cout << "======" << endl;
return;
}
private:
vector<int> data; //用动态数组存放数据。
}
int main() {
Stack s;
string op; //输入字符串"push"代表要执行压栈操作,"pop"要执行出栈操作。
int val; //要压栈的数据。
while(cin >> op) {
if (op == "push") {
cin >> val;
s.push(val);
} else if (op == "pop") {
s.pop();
} else if (op == "size") { //要返回栈中的元素数量。
cout << size:<< s.size() << endl;
} else if (op == "output") { //要输出栈中所有元素。
s.output();
}
}
return 0;
}
运行:
push 1
push 2
push 3
output
======
3
2
1
======
pop
output
======
2
1
======
push 4
output
======
4
2
1
======
不依赖vector实现栈
using namespace std;
class Stack {
public:
Stack(int n=100) { //初始化栈
top = -1;
data = new int[n];
}
void push(int x) { //压栈
top += 1; //栈顶指针向上移动一位。
data[top] = x;
return;
}
void pop() { //出栈
if(empty()) return; //出栈之前先判空
top -= 1; //出栈,仅指针移动即可。
return;
}
bool empty() { //判空
return top == -1; //判断栈顶指针是否等于-1即可
}
int size() { //返回栈内元素数量
return top + 1; //top+1就是栈中元素的个数。
}
void output() { //输出栈中所有元素
cout << "======" << endl;
for(int i = top; i >= 0; i--) { //逆序地遍历vector中的每一个元素
cout << data[i] <<endl;
}
cout << "======" << endl;
return;
}
private:
int *data, top; //top是栈顶指针,data是数据的数组。
}