1.1 栈的一个实际需求
请输入一个表达式
计算式:[722-5+1-5+3-3] 点击计算【如下图】
- 请问: 计算机底层是如何运算得到结果的? 注意不是简单的把算式列出运算,因为我们看这个算式 7 * 2 * 2 -5, 但是计算机怎么理解这个算式的(对计算机而言,它接收到的就是一个字符串),我们讨论的是这个问题。-> 栈
1.2 栈的介绍
- 栈的英文为(stack)
- 栈是一个先入后出(FILO-First In Last Out)的有序列表。
- 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
- 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除
- 图解方式说明出栈(pop)和入栈(push)的概念
1.3 栈的快速入门
- 用数组模拟栈的使用,由于栈是一种有序列表,当然可以使用数组的结构来储存栈的数据内容, 下面我们就用数组模拟栈的出栈,入栈等操作。
- 实现思路分析,并画出示意图
- 代码实现:
- ArrayStack 类
// 定义一个ArrayStack表示栈
class ArrayStack {
private int maxSize; // 栈的大小
private int[] stack; // 数组,数组模拟栈,数据就存放该数组中
private int top = -1; // top表示栈顶,初始化为-1
public ArrayStack(int maxSize) {
super();
this.maxSize = maxSize;
stack = new int[maxSize];
}
// 栈满
public boolean isFull() {
return top == maxSize - 1;
}
// 栈空
public boolean isEmpty() {
return top == -1;
}
// 入栈
public void push(int value) {
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
// 出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据~");
}
int value = stack[top];
top--;
return value;
}
// 遍历
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据~~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
- ArrayStackDemo 类
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
while (loop) {
System.out.println("show:表示显示栈");
System.out.println("exit:退出程序");
System.out.println("push:表示添加数据到栈(入栈)");
System.out.println("pop:表示从栈取出数据(出栈)");
System.out.println("请输入你的选择");
key = scanner.next();
switch (key) {
case "show":
stack.list();
break;
case "push":
System.out.println("请输入一个数");
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int res = stack.pop();
System.out.printf("出栈的数据是%d\n", res);
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
4 栈实现综合计算器(中缀表达式)
使用栈来实现综合计算器
思路分析(图解)
代码实现
- CalculatorArrayStack 类
// 定义一个CalculatorArrayStack表示栈
class CalculatorArrayStack {
private int maxSize; // 栈的大小
private int[] stack; // 数组,数组模拟栈,数据就存放该数组中
private int top = -1; // top表示栈顶,初始化为-1
public CalculatorArrayStack(int maxSize) {
super();
this.maxSize = maxSize;
stack = new int[maxSize];
}
// 栈满
public boolean isFull() {
return top == maxSize - 1;
}
// 栈空
public boolean isEmpty() {
return top == -1;
}
// 入栈
public void push(int value) {
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
// 出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,没有数据~");
}
int value = stack[top];
top--;
return value;
}
// 返回栈顶的值,但不出栈
public int peek() {
return stack[top];
}
// 遍历
public void list() {
if (isEmpty()) {
System.out.println("栈空,没有数据~~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
// 返回运算符的优先级,优先级使用数字表示
// 数字越大则优先级越高
// 只支持 +、-、*、/
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
} else {
return -1;
}
}
// 判断是不是一个运算符
public boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
// 计算方法
public int cal(int num1, int num2, int oper) {
int res = 0;
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}
- Calculator 类
public class Calculator {
public static void main(String[] args) {
String expression = "3+2*6-2";
// 创建数栈、符号栈
CalculatorArrayStack numStack = new CalculatorArrayStack(10);
CalculatorArrayStack operStack = new CalculatorArrayStack(10);
// 定义相关变量
int index = 0;
int num1 = 0, num2 = 0, oper = 0, res = 0;
char ch = ' ';// 每次扫描得到的char保存到ch
String keepNum = "";// 用于拼接多位数
while (true) {
// 1. 通过一个 index 值(索引),来遍历我们的表达式
ch = expression.substring(index, index + 1).charAt(0);
if (operStack.isOper(ch)) { // 3. 如果发现扫描到是一个符号, 就分如下情况
if (!operStack.isEmpty()) {
// 3.2 如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符,
// 就需要从数栈中pop出两个数,在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,
// 然后将当前的操作符入符号栈, 如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈.
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
operStack.push(ch);
} else {
operStack.push(ch);
}
} else { // 3.1 如果发现当前的符号栈为 空,就直接入栈
operStack.push(ch);
}
} else { // 2. 如果我们发现是一个数字, 就直接入数栈
// numStack.push(ch - 48); // 字符 '1' 转化为 数字 1
// 1.当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
// 2.在处理数,需要向expression的表达的index 后面看一位,如果是数就进行扫描,如果是符号才入栈
// 3.因此我们需要定义一个变量 字符串,用于拼接
keepNum += ch;
// ch 为表达式的最后一位
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
} else {
if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
while (true) {
// 4. 当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行.
// 符号栈为空,则计算到最后的结果,此时数栈中只有一个数字【结果】
if (operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
// 5. 最后在数栈只有一个数字,就是表达式的结果
System.out.printf("表达式 %s = %d ", expression, numStack.pop());
}
}