用c++里的stack容器很容易做出来
1 #include <bits/stdc++.h> 2 using namespace std; 3 int main() { 4 stack<int> s; 5 int n; 6 cin >> n; 7 while (n--) { 8 string op; 9 int x; 10 cin >> op; 11 if (op == "push") { 12 cin >> x; 13 s.push(x); 14 } else if (op == "pop") { 15 s.pop(); 16 } else if (op == "empty") { 17 if (s.empty()) { 18 cout << "YES" << endl; 19 } else { 20 cout << "NO" << endl; 21 } 22 } else if (op == "query") { 23 cout << s.top() << endl; 24 } 25 } 26 return 0; 27 }
现在考察用数组手动实现一个栈
1 #include <bits/stdc++.h> 2 using namespace std; 3 const int N = 100010; 4 int stk[N], tt; 5 int main() { 6 int m; 7 cin >> m; 8 while (m--) { 9 string s; 10 int x; 11 cin >> s; 12 if (s == "push") { 13 cin >> x; 14 stk[++tt] = x; 15 } else if (s == "pop") { 16 tt--; 17 } else if (s == "empty") { 18 if (tt > 0) { 19 cout << "NO" << endl; 20 } else { 21 cout << "YES" << endl; 22 } 23 } else if (s == "query") { 24 cout << stk[tt] << endl; 25 } 26 } 27 return 0; 28 }