一、堆栈
基本操作:
#include <stack>
stack<int> s;
s.size() // 栈内元素个数
s.empty() // 判断栈是否为空
s.push(x) // 将x入栈
s.pop() // 栈顶出栈
s.top() // 栈顶元素
while(!s.empty()) // 栈的清空(STL中没有实现栈的清空)
{
s.pop();
}
注:在使用pop() 和 top() 函数之前,必须先使用 empty() 函数判断栈是否为空。
eg1. 括号匹配问题
思路分析:
建立堆栈,存放左括号的下标值。而对于右括号,只需要判断堆栈中是否还存在元素(左括号)。若存在则匹配成功,否则意味着匹配失败。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
stack<int> s; // 字符下标堆栈 (栈中之存储左括号,如果右括号入栈意味着该括号存在不匹配
string str;
char ans[105];
int main()
{
freopen("input.txt", "r", stdin);
while(cin >> str)
{
for(int i=0; i<str.size(); i++)
{
if(str[i] == '(')
{
s.push(i); // 左括号全部入栈
ans[i] = ' '; // 对应显示数组填空格
}
else if(str[i] == ')')
{
if(!s.empty()) // 栈非空,有匹配的括号
{
s.pop(); // 元素出栈之前一定要检查栈是否为空!!!
ans[i] = ' ';
}
else // 栈空,无匹配项
{
ans[i] = '?';
}
}
else
{
ans[i] = ' ';
}