栈
后进先出
1. 顺序栈
- 定义栈顶top,初始值为-1
- 入栈:stack[++top] = data
- 出栈:return stack[top–]
- 栈空:top == -1
- 栈满:top == capacity - 1
public class MyStack<E> {
// 栈的最大容量
private int capacity;
// 采用数组实现栈
private E[] stack;
// 栈顶索引
private int top = -1;
public MyStack(int capacity) {
this.capacity = capacity;
stack = (E[]) new Object[capacity];
}
public boolean empty() {
return top == -1;
}
public boolean full() {
return top == capacity - 1;
}
public int size() {
return top + 1;
}
public E push(E item) {
if (full()) {
throw new RuntimeException("full");
}
// 先将top++,在赋值
stack[++top] = item;
return item;
}
public E pop() {
if (empty()) {
throw new RuntimeException("empty");
}
// 先获取栈顶值,再将top--
return stack[top--];
}
public E peek() {
if (empty()) {
throw new RuntimeException("empty");
}
return stack[top];
}
}
2. 中缀表达式
利用栈计算中缀表达式结果思路:
- 从左至右遍历中缀表达式,依次取出表达式的每一个字符
- 若取出的字符是运算符:
- 如果符号栈为空,直接入符号栈
- 如果符号栈不为空,判断当前操作符与栈顶操作符的优先级
- 当前操作符优先级小于或等于栈顶操作符:计算,然后将当前操作符压入符号栈
- 当前操作符优先级大于栈中的操作符,直接入符号栈
- 若取出的字符是操作数:分析出完整的运算数
- 如果当前已经是最后一位,则入栈
- 如果下一个字符是符号,则入栈
- 计算,直到符号栈为空
- 最后数字栈中仅剩的数字就是表达式结果
- 计算过程:
- 从数字栈pop出两个数
- 从符号栈顶pop出一个符号
- 计算,将运算结果压入数字栈
中缀表达式代码实现:
import java.util.Stack;
public class Calculator {
// 获取符号优先级
public static int priority(char operation) {
if (operation == '*' || operation == '/')
return 1;
else if (operation == '+' || operation == '-')
return 0;
else
return -1;
}
// 判断字符是否为符号
public static boolean isOperation(char value) {
return value == '+' || value == '-' || value == '*' || value ==