栈(stack)是一种先进后出的基本数据结构
一、实现
(一)手写
需要一个栈顶指针(指向空位置),数组作栈
(在结构体内写更好)
#include <iostream>
using namespace std;
#define EMPTY -9999999
int stack[1001];
int top = 1;
int n, tmp;
void push(const int x) {
stack[top ++] = x;
}
bool empty() {
if(top == 1) return true;
return false;
}
int pop() {
if(empty()) return EMPTY;
return stack[-- top];
}
int Func_top() {
return stack[top-1];
}
int main() {
cin >> n;
for(int i=0; i<n; i++) {
cin >> tmp;
push(tmp);
}
while(!empty()) {
cout << Func_top() << " ";
pop();
}
return 0;
}
(二)C++ STL
stack<int> a;
常用操作:
a. push(x) 将x入栈
a. top() 访问栈顶元素
a. pop() 弹出(不返回)栈顶元素
a. empty() 判断栈是否为空
a.size() 返回栈中元素个数
#include <iostream>
#include <stack>
using namespace std;
stack<int> a;
int n, tmp;
int main() {
cin >> n;
for(int i=0; i<n; i++) {
cin >> tmp;
a.push(tmp);
}
while(!a.empty()) {
cout << a.top() << " ";
a.pop();
}
return 0;
}
二、应用
判断括号是否合法。‘('入栈,')'出栈即可
#include <iostream>
#include <stack>
using namespace std;
char a[10001];
int n;
bool Judge(char *c) {
int pos = 0;
stack<int> S;
while(c[pos] != '@') {
if(c[pos] == '(') S.push(c[pos]);
else if(c[pos] == ')') {
if(!S.empty() && S.top() == '(') S.pop();
else return false;
}
pos ++;
}
if(S.empty()) return true;
return false;
}
int main() {
cin >> a;
if(Judge(a)) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}
判断合法出栈序列。(入栈序列1,2,3,..., n)
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
//判断合法出栈序列
int n, w;
int s[1001];
stack<int> S;
int main() {
cin >> n;
for(int i=1; i<=n; i++) cin >> s[i];
w = 1;
for(int i=1; i<=n; i++) {
while(S.empty() || S.top() != s[i]) {
if(w > n) {
cout << "NO" << endl;
return 0;
}
S.push(w ++);
}
if(S.top() == s[i]) S.pop();
}
if(S.empty()) cout << "YES" << endl;
else cout << "NO" << endl;
return 0;
}