数组实现栈1
//数组实现栈1
#include<bits/stdc++.h>
using namespace std;
int n, m, top;
int st[100010];
char str[100];
int main(){
scanf("%d", &n);
for (int i = 1; i <= n; i++){
scanf("%s", &str);
if (str[1] == 'u'){
int x;
cin >> x;
st[++top] = x;
}
else if (str[0] == 't'){
printf("%d\n", st[top]);
}
else {
top--;
}
}
return 0;
}
数组实现栈2
//数组实现栈2
#include<bits/stdc++.h>
using namespace std;
int n, m, top;
int st[100010];
char str[100];
int main(){
cin >> n;
for (int i = 1; i <= n; i++){
scanf("%s", &str);
if (str[2] == 's'){
int x;
cin >> x;
st[++top] = x;
}
else if (str[0] == 'q'){
int y;
cin >> y;
printf("%d\n", st[top - y + 1]);
}
else {
top--;
}
}
return 0;
}
出栈序列判断
//出栈序列判断
#include<bits/stdc++.h>
using namespace std;
int n, m, top;
int st[100010];
int main(){
scanf("%d", &n);
int l = 0;
for (int i = 1; i <= n; i++){
int x;
scanf("%d", &x);
if (st[top] != x){
for (int j = l + 1; j <= x; j++){
st[++top] = j;
printf("push %d\n", j);
}
l = x;
}
printf("pop\n");
top--;
}
return 0;
}
括号序列
//括号序列
#include<bits/stdc++.h>
using namespace std;
int n, m, top;
char s[100010];
char st[100010];
bool ok = 1;
int main(){
scanf("%d%s", &n, s);
for (int i = 0; i < n; i++){
if (s[i] == '(' || s[i] == '[')
st[++top] = s[i];
else {
if (!top){
printf("No\n");
return 0;
}
else {
if (s[i] == ')'){
if (st[top] == '(')
top--;
else
ok = 0;
}
if (s[i] == ']'){
if (st[top] == '[')
top--;
else
ok = 0;
}
}
}
}
if (top){
ok = 0;
}
if (ok){
printf("Yes\n");
}else {
printf("No\n");
}
return 0;
}
字符串处理1
//字符串处理1
#include<bits/stdc++.h>
using namespace std;
int n, top;
char s[100010];
char st[100010];
int main(){
scanf("%d%s", &n, s);
for (int i = 0; i < n; i++){
if (st[top] != s[i]){
st[++top] = s[i];
}
else {
top--;
}
}
for (int i = 1; i <= top; i++){
printf("%c", st[i]);
}
}
字符串处理2
//字符串处理2
#include<bits/stdc++.h>
using namespace std;
int n, top;
char s[100010];
char st[100010];
int main(){
scanf("%d%s", &n, s);
for (int i = 0; i < n; i++){
if (st[top] - s[i] != 32 && st[top] - s[i] != -32){
st[++top] = s[i];
}
else {
top--;
}
}
for (int i = 1; i <= top; i++){
printf("%c", st[i]);
}
}
总结
栈的底层实现逻辑其实就是数组,使用数组模拟栈可以做到STL所做不到的,比如query k(查找栈顶往下第k个元素)操作,所以数组模拟栈很常用,灵活度也更高。