题解 | 【模板】栈
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf?tpId=308&tqId=2111163&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
#include <iostream> using namespace std; int main() { int n; cin >> n; string a; int x[n], len=0; for (int i=0; i<n; ++i) { cin >> a; if (a == "pop") { if (len > 0) { cout << x[--len] << endl; } else cout << "error" << endl; } else if (a == "top") { if (len > 0) { cout << x[len-1] << endl; } else cout << "error" << endl; } else { int t; cin >> t; x[len++] = t; } } } // 64 位输出请用 printf("%lld")
#include <iostream> #include <type_traits> using namespace std; class stack { private: int x[100000]; int top_index = -1; public: int size() { return top_index+1; } void push(int i) { x[++top_index] = i; } int pop() { return x[top_index--]; } int top() { return x[top_index]; } }; int main() { int n; cin >> n; string a; stack x; for (int i = 0; i < n; ++i) { cin >> a; if (a == "pop") { if (x.size() > 0) { cout << x.pop() << endl; } else cout << "error" << endl; } else if (a == "top") { if (x.size() > 0) { cout << x.top() << endl; } else cout << "error" << endl; } else { int t; cin >> t; x.push(t); } } } // 64 位输出请用 printf("%lld")