栈的定义
栈是一种先入后出的数据结构,如图所示结构
在C++中给出了相应的数据结构
stack<栈内元素类型> st;
栈的基本操作
入栈Push
操作如图所示,从栈顶插入一个元素
C++中对应的操作
st.push(元素)
取出栈顶元素Top
取出栈顶元素的值
C++中对应操作
栈顶元素的值 = st.top()
出栈Pop
从栈顶弹出一个元素
C++中对应操作
st.pop()
数组模拟实现栈
stk[] 存储元素的数组
tt为 栈顶
acwing828. 模拟栈
输入样例:
10
push 5
query
push 6
pop
query
pop
empty
push 4
query
empty
All in:
#include <iostream>
using namespace std;
const int N = 100010;
int tt;
int stk[N];
int main()
{
int m;
scanf("%d",&m);
while (m --)
{
string op;
cin >> op;
if (op == "push")
{
int x;
scanf("%d", &x);
stk[++ tt] = x;//向栈顶插入元素
}
if (op == "pop") tt --;
if (op == "query") printf("%d\n",stk[tt]);
if (op == "empty") //empty判断栈里是否为空
{
if (tt > 0) printf ("NO\n");
else printf("YES\n");
}
}
}
表达式求值(C++)
acwing3302. 表达式求值
All in:
#include <iostream>
#include <algorithm>
#include <stack>
#include <unordered_map>
#include <cstring>
using namespace std;
const int N = 100010;
unordered_map<char, int> pr{{'-', 1}, {'+', 1}, {'*', 2}, {'/', 2}};
char str[N];
stack<int> num;//存储数字
stack<char> op;//存储操作符
void eval()
{
int num2 = num.top();
num.pop();
int num1 = num.top();
num.pop();
int x = 0;
if (op.top() == '-')
{
x = num1 - num2;
}
else if (op.top() == '+')
{
x = num1 + num2;
}
else if (op.top() == '*')
{
x = num1 * num2;
}
else if (op.top() == '/')
{
x = num1 / num2;
}
op.pop();
num.push(x);
}
int main()
{
scanf("%s", str);
int len = strlen(str);
for (int i = 0; i < len; i ++ )
{
//如果是数字
if (str[i] >= '0' && str[i] <= '9')
{
int x = 0, j = i;
while (j < len && str[j] >= '0' && str[j] <= '9')
{
x = x * 10 + str[j] - '0';
j ++;
}
i = j - 1;
num.push(x);
}
else if (str[i] == '(')
{
op.push(str[i]);
}
else if (str[i] == ')')
{
while (op.top() != '(') eval();
op.pop();
}
else
{
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[str[i]]) eval();
op.push(str[i]);
}
}
while(op.size()) eval();
printf("%d\n", num.top());
}
中缀转后缀(C++)
后缀表达式又称逆波兰表达式
中缀转后缀思路
1.遇到数字,加入后缀表达式中
2.遇到左括号,加入存运算符的栈中
3.遇到右括号,弹出存运算符的栈中元素直到遇到左括号,最后要将左括号弹出
4.遇到加减乘除,栈不为空,栈顶不为左括号,栈顶元素的优先级大于等于即将插入的运算符,弹出栈内元素
中缀转后缀C++实现
#include <iostream>
#include <stack>
#include <unordered_map>
#include <cstring>
using namespace std;
const int N = 100010;
unordered_map<char, int> pr{{'-', 1}, {'+', 1}, {'*', 2}, {'/', 2}};
stack<char> op;//存运算符
string res;//存后缀
char str[N];//读入中缀
int main()
{
scanf("%s", str);
int len = strlen(str);
for (int i = 0; i < len; i ++ )
{
char c = str[i];
//如果是数字 直接加到后缀表达式中
if (c >= '0' && c <= '9')
{
res += c;
}
//左括号 入栈
else if (c == '(') op.push(c);
//右括号 弹出栈内元素直到遇到第一个右括号
else if (c == ')')
{
while (op.top() != '(')
{
res += op.top();
op.pop();
}
op.pop();
}
//加减乘除
else
{
//当栈不为空 栈顶不为右括号 栈顶优先级大于等于即将插入元素的优先级
//弹出栈内元素 加入后缀表达式中
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c])
{
res += op.top();
op.pop();
}
op.push(c);
}
}
//当栈不为空 就将剩余的操作符加入后缀表达式
while (op.size())
{
res += op.top();
op.pop();
}
cout << res << endl;
}