STL之stack介绍(以数字游戏为例)

上一篇介绍queue的性质及其用法,queue是先进先出,而stack就与之相反,是先进后出的。
stack与queue一样没有遍历查询的功能,可以新开个数组来进行记录。
基本定义 stack<int> a;
基本操作:
a.top() 返回栈顶元素
a.pop() 移除栈顶元素
a.empty() 判断stack是否为空
a.size() 返回栈中元素个数
a.push(number) 在栈顶中增加元素
数字游戏为例,简单介绍一下stack的运用。

#include<bits/stdc++.h>
using namespace std;
const int _MAXN=1e5;
int main(){
 int n;
 cin>>n;
 stack<int>a;
 for(int i=0;i<n;i++){
  int num;
  cin>>num;
  while(!a.empty()){
   if(a.top()<num) a.pop();
   else{
    break;
   }
  }
  a.push(num);
 }
 int i;
 int ans[_MAXN+10];
 memset(ans,0,sizeof(ans));
 for(i=0;!a.empty();i++){
  ans[i]=a.top();
  a.pop();
 }
 for(i=i-1;i>=0;i--) cout<<ans[i]<<endl;
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
后缀表达式 #include <iostream> #include <stack> #include <string> using namespace std; // 判断是否为数字 bool is_digit(char c) { return c >= '0' && c <= '9'; } // 判断是否为操作符 bool is_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } // 获取操作符的优先级 int get_priority(char op) { if (op == '+' || op == '-') { return 1; } else if (op == '*' || op == '/') { return 2; } else { return 0; } } // 将中缀表达式转换为后缀表达式 string infix_to_postfix(string infix) { string postfix; // 后缀表达式 stack<char> op_stack; // 操作符 // 遍历中缀表达式 for (int i = 0; i < infix.size(); i++) { char c = infix[i]; if (is_digit(c)) { // 如果是数字,直接加入后缀表达式 postfix += c; } else if (c == '(') { // 如果是左括号,入 op_stack.push(c); } else if (c == ')') { // 如果是右括号,弹出中操作符直到遇到左括号 while (!op_stack.empty() && op_stack.top() != '(') { postfix += op_stack.top(); op_stack.pop(); } if (!op_stack.empty()) { op_stack.pop(); // 弹出左括号 } } else if (is_operator(c)) { // 如果是操作符 // 弹出中优先级高于等于当前操作符的操作符 while (!op_stack.empty() && get_priority(op_stack.top()) >= get_priority(c)) { postfix += op_stack.top(); op_stack.pop(); } op_stack.push(c); // 当前操作符入 } } // 弹出中剩余的操作符 while (!op_stack.empty()) { postfix += op_stack.top(); op_stack.pop(); } return postfix; } int main() { string infix = "3+(4*5/(6-7))"; string postfix = infix_to_postfix(infix); cout << postfix << endl; // 345*67-/+ return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值