目录
Stack 是一种数据结构,它的特点是先进后出(Last In First Out,LIFO)。这意味着最后进入栈的元素将首先被弹出。栈可以用数组或链表来实现。
1、std::stack 的基本操作包括:
1. push:将元素压入栈顶。
2. pop:弹出栈顶元素。
3. peek:查看栈顶元素。
4. isEmpty:判断栈是否为空。
2、std::stack 的应用包括:
(1)表达式求值:可以使用栈来实现中缀表达式的转换和计算。
(2)函数调用:当一个函数被调用时,它的局部变量和参数被压入栈中,当函数执行完毕,这些变量和参数被弹出。
(3)括号匹配:可以使用栈来检查一个字符串中的括号是否匹配。
(4)浏览器的前进和后退:可以使用两个栈来实现浏览器的前进和后退功能。
3、std::stack 实例
以下是一个使用 std::stack 的简单示例,来实现一个基本的计算器:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main() {
stack<int> numStack;
stack<char> opStack;
string input;
cout << "Enter an expression: ";
getline(cin, input);
for (int i = 0; i < input.length(); i++) {
if (isdigit(input[i])) {
int num = 0;
while (i < input.length() && isdigit(input[i])) {
num = num * 10 + (input[i] - '0');
i++;
}
numStack.push(num);
i--;
}
else if (input[i] == '(') {
opStack.push(input[i]);
}
else if (input[i] == ')') {
while (!opStack.empty() && opStack.top() != '(') {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
char op = opStack.top();
opStack.pop();
int result;
if (op == '+') {
result = num1 + num2;
}
else {
result = num1 - num2;
}
numStack.push(result);
}
opStack.pop();
}
else if (input[i] == '+' || input[i] == '-') {
while (!opStack.empty() && opStack.top() != '(') {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
char op = opStack.top();
opStack.pop();
int result;
if (op == '+') {
result = num1 + num2;
}
else {
result = num1 - num2;
}
numStack.push(result);
}
opStack.push(input[i]);
}
}
while (!opStack.empty()) {
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
char op = opStack.top();
opStack.pop();
int result;
if (op == '+') {
result = num1 + num2;
}
else {
result = num1 - num2;
}
numStack.push(result);
}
cout << "Result: " << numStack.top() << endl;
return 0;
}
该示例使用两个栈:一个存储数字,另一个存储运算符。它从用户输入读取一个表达式,然后依次处理每个字符。如果检测到数字,则将其转换为整数并将其压入数字栈中。如果检测到左括号,则将其压入运算符栈中。如果检测到右括号,则从栈中弹出运算符和数字,执行相应的运算,并将结果压入数字栈中,直到遇到左括号。如果检测到加号或减号,则从栈中弹出运算符和数字,执行相应的运算,并将结果压入数字栈中,直到遇到左括号或更低优先级的运算符。最后,将栈中剩余的运算符和数字弹出并执行相应的运算,最终结果为数字栈中的顶部元素。