STL初步——栈Stack

『写在前面的一些基础语法』

1.栈(stack)的一些特性

  • 操作原则:后进先出(Last In First Out ,LIFO)。
  • 仅允许在表的一端进行插入和删除运算的线性表。
  • 允许运算的一端被称为栈顶(Top),相对地,把另一端称为栈底(Bottom)

2.定义 和 赋值

  • stack<int> s;       
  • stack<int> s1(s2); //复制栈

3.一些基础的操作

  • s.push(x);//压入一个数据到栈中
  • s.pop()l//弹出栈顶数据
  • s.top();//返回栈顶的元素,但不弹出
  • s.empty();//判断栈是否为空
  • s.size();//返回栈中的元素个数

『上题上题』

【集合栈计算机】

有一个专门为了集合运算而设计的“集合栈”计算机。该机器有一个初始为空的栈,并且支持以下操作:<

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
后缀表达式 #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; }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值