题解 | #【模板】栈#
【模板】栈
https://www.nowcoder.com/practice/104ce248c2f04cfb986b92d0548cccbf
#include <cctype> #include <iostream> #include <cstring> using namespace std; class Stack { private: enum {Max = 100000}; int data[Max]; int top; public: Stack() { this->top = -1; } void pushStack(int n) { this->data[++top] = n; } void popStack() { if (top != -1) cout << data[top--] << endl; else cout << "error" << endl; } void topStack() { if (top != -1) cout << data[top] << endl; else cout << "error" << endl; } }; int main() { int times; char str[100] = {0}; char act[10] = {0}; int num = 0; bool haveSpace = false; Stack s; cin >> times; // 建议此处更换为string处理 for (int i = 0; i <= times; i++) { memset(str, 0, sizeof(str)); memset(act, 0, sizeof(act)); cin.getline(str, sizeof(str)); for (int j = 0; str[j] != '\0'; j++) { if (isspace(str[j])) { memcpy(act, str, j); num = atoi(&str[j + 1]); haveSpace = true; } } if (false == haveSpace) memcpy(act, str, 3); if (!strcmp(act, "push")) s.pushStack(num); else if (!strcmp(act, "pop")) s.popStack(); else if (!strcmp(act, "top")) s.topStack(); haveSpace = false; } }