/**
* 栈的应用:括号匹配、表达式求值、递归
* 如:表达式求值:a+b-a*((c+d)/e-f)+g
* 如:求斐波那契数列 0 1 1 2 3 5 8 13 ...
*/
class Solution {
// 1.递归(递归会用工作栈存储返回点、局部变量、传入参数)
int Fib(int n) {
if (n == 0) return 0;
else if (n == 1) return 1;
else return Fib(n - 1) + Fib(n - 2);
}
// 2.使用栈实现求斐波那契数列
int Fib2(int n) {
int fv0 = 0, fv1 = 1;
Stack<Integer> stack = new Stack<>();
for (int i = n; i >= 2; i--) {
stack.add(i);
}
/*
* 栈的作用? 出栈2,表示计算Fib(2)
* 和while循环有什么区别?
* 和递归中的栈有什么区别? 递归中栈有重复计算
*/
while (!stack.isEmpty()) {
stack.pop(); // 出栈计算
int temp = fv0 + fv1;
fv0 = fv1;
fv1 = temp;
}
if (n == 0) return fv0;
return fv1;
}
// 3.使用循环求斐波那契数列
int Fib3(int n) {
int first = 0, second = 1;
while (n >= 1) {
int temp = first;
first = second;
second = temp + second;
n--;
}
return first;
}
/**
* param = 输入中序表达式
* 1.先将中序表达式转为后序表达式(运算符栈)
* 2.根据后序表达式计算求值(运算数栈)
*/
public void reckon(String inOrder) {
// 1.中序转后序
StringBuilder postOrder = new StringBuilder();
Stack<Character> operatorStack = new Stack(); // 运算符栈
operatorStack.push('#');
HashMap<Character, Integer> op = new HashMap<>();
op.put('#', 0); // 数字表示优先级
op.put('(', 1);
op.put('+', 2);
op.put('-', 2);
op.put('*', 3);
op.put('/', 3);
op.put(')', 1);
for (int i = 0; i < inOrder.length(); i++) {
char ch = inOrder.charAt(i);
if (ch >= 'a' && ch <= 'z') postOrder.append(ch);
else {
// ( + - * / )
if (op.get(ch) > op.get(operatorStack.peek()) || ch == '(') { // 运算符高或为'('直接入栈
operatorStack.push(ch);
} else {
if (ch == ')') { // 弹出括号内的所有运算符
while (operatorStack.peek() != '(') {
postOrder.append(operatorStack.pop());// 出栈
}
operatorStack.pop(); // 弹出'('
} else { // 弹出优先级高的运算符再入栈
while (op.get(ch) <= op.get(operatorStack.peek())) {
postOrder.append(operatorStack.pop());// 出栈
}
operatorStack.push(ch); // 压栈
}
}
}
}
while (operatorStack.peek() != '#') {
postOrder.append(operatorStack.pop());
}
System.out.println("后缀表达式:" + postOrder.toString());
Stack<Character> operationNumberStack = new Stack(); // 运算数栈
for (char ch : postOrder.toString().toCharArray()) {
/**
* 1.遇到操作数:操作数进栈
* 2.遇到操作符:栈顶弹出两操作数A = stack.pop(), B=stack.pop() 运算B op A后将结果压栈
* 循环以上步骤最后栈内元素即为表达式结果
*/
}
}
public static void main(String[] args) {
Solution solution = new Solution();
// 栈在递归中的应用
System.out.println(solution.Fib(7));
System.out.println(solution.Fib2(7));
System.out.println(solution.Fib3(7));
// 栈在表达式求值中的应用
solution.reckon("a+b-a*((c+d)/e-f)+g");
}
}
1.栈的应用
最新推荐文章于 2023-08-26 10:48:44 发布