栈的数组实现
- 确定好栈底的元素
- 边界条件
- 变化过程
栈底是-1
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 1e5 + 10; int tt; int stk[maxn]; void init() { tt = 0; // tt = 0的时候为空,因为如果不为空的话他肯定不会在0的位置 } void push(int x) { stq[tt++] = x; } void pop() { if(tt > 0) tt--; } int query() { return stq[tt - 1]; } bool empty() { return tt > 0 ? false : true; } void read() { int x; string op; cin >> op; if(op == "push") { cin >> x; push(x); } else if(op == "query") { cout << query() << endl; } else if(op == "pop") { pop(); } else { if(empty()) cout << "YES" << endl; else cout << "NO" << endl; } } int main() { int m; cin >> m; while (m -- ) { read(); } return 0; }
栈底是0
#include <iostream> using namespace std; const int N = 100010; int m; int stk[N], tt; int main() { cin >> m; while (m -- ) { string op; int x; cin >> op; if (op == "push") { cin >> x; stk[ ++ tt] = x; } else if (op == "pop") tt -- ; else if (op == "empty") cout << (tt ? "NO" : "YES") << endl; else cout << stk[tt] << endl; } return 0; }
队列的数组实现
队尾是0
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 1e5 + 10; int tt, kk; int stq[maxn]; void init() { tt = 0; kk = 0; } void push(int x) { stq[kk++] = x; } void pop() { if(tt < kk) tt++; else printf("-1"); } int query() { return stq[tt]; } bool empty() { return tt == kk ? false : true; } void read() { int x; string op; cin >> op; if(op == "push") { cin >> x; push(x); } else if(op == "query") { cout << query() << endl; } else if(op == "pop") { pop(); } else { if(empty()) cout << "YES" << endl; else cout << "NO" << endl; } } int main() { int m; init(); cin >> m; while (m -- ) { read(); } return 0; }
队尾是-1
#include <iostream> using namespace std; const int N = 100010; int m; int q[N], hh, tt = -1; int main() { cin >> m; while (m -- ) { string op; int x; cin >> op; if (op == "push") { cin >> x; q[ ++ tt] = x; } else if (op == "pop") hh ++ ; else if (op == "empty") cout << (hh <= tt ? "NO" : "YES") << endl; else cout << q[hh] << endl; } return 0; }
来源:https://www.cnblogs.com/WalterJ726/p/12395804.html