介绍
- 栈是一个先入后出(FILO)的有序列表
- 栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)
- 根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素正好相反,最后放入的元素最先删除,最先放入的元素最后删除
图解
应用场景
- 子程序的调用:在跳往子程序前,会先将下一个指令的地址存到堆栈中,直到子程序执行完再将地址取出,以回到原来的程序中
- 处理递归调用:和子程序调用类似,只是除了存储下一个指令的地址外,也将参数、区域变量等数据存入堆栈中
- 表达式的转换[中缀表达式转后缀表达式]与求值
- 二叉树的遍历
- 图形的深度优先搜索法
使用数组模拟栈
思路分析
- 定义一个top表示栈顶,初始化为-1
- 入栈的操作:当有数据加入到栈时,top++; stack[top] = data;
- 出栈的操作:int value = stack[top]; top--;
代码实现
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
//先创建一个ArrayStack对象表示栈
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("程序退出");
}
}
//定义一个 ArrayStack表示栈
class ArrayStack {
private int maxSize; // 栈的大小
private int[] stack;
private int top = -1;// top表示栈顶,初始化为-1
//构造器
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//栈满
public boolean isFull() {
return top == maxSize - 1;
}
//栈空
public boolean isEmpty() {
return top == -1;
}
//入栈-push
public void push(int value) {
//先判断栈是否满
if(isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
//出栈-pop
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]);
}
}
}
栈实现综合计算器(中缀表达式)
思路分析
- 通过一个index值(索引)来遍历表达式
- 如果是数字就直接入数栈
- 如果是符号,分如下情况:
- 如果当前符号栈为空,,就直接入栈
- 如果当前符号栈有操作符,就进行比较:如果当前的操作符的优先级小于或者等于栈中的操作符,就需要从数栈中pop出两个数,再从符号栈pop出一个符号,进行运算,得到的结果入数栈,然后将当前操作符如符号栈;如果当前操作符的优先级大于栈中的操作符,就直接入符号栈
- 当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运行
- 最后在数栈中只有一个数字,就是表达式的结果
代码实现
public class JosephusProblem {
public static void main(String[] args) {
String expression = "7*2*(5-2)+1-5+3-4"; // 37
// 创建两个栈,数栈和符号栈
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
// 定义需要的相关变量
int index = 0;// 用于扫描
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' '; // 将每次扫描得到的char保存到ch
String keepNum = ""; // 用于拼接多位数
// 开始while循环的扫描expression
while (true) {
// 依次得到expression的每一个字符
ch = expression.substring(index, index + 1).charAt(0);
// 判断ch是什么,然后做相应的处理
if (operStack.isOper(ch) || ch == '(' || ch == ')') {// 如果是运算符或括号
if (ch == '(') {
operStack.push(ch);
} else if (ch == ')') {
while (operStack.peek() != '(') {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
operStack.pop(); // 弹出'('
} else { // 如果是运算符
if (!operStack.isEmpty()) {
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 {
operStack.push(ch);
}
}
} else { // 如果是数,则直接入数栈
keepNum += ch;
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
} else {
if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0)) || expression.substring(index + 1, index + 2).charAt(0) == '(' || expression.substring(index + 1, index + 2).charAt(0) == ')') {
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
while (!operStack.isEmpty()) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
// 将数栈的最后数pop出就是结果
int res2 = numStack.pop();
System.out.printf("表达式 %s = %d", expression, res2);
}
}
// 定义一个 ArrayStack2表示栈,需要扩展功能
class ArrayStack2 {
private int maxSize; // 栈的大小
private int[] stack;
private int top = -1;
// 构造器
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
// 增加一个方法,可以返回当前栈顶的值,但不是真正的pop
public int peek() {
return stack[top];
}
// 栈满
public boolean isFull() {
return top == maxSize - 1;
}
// 栈空
public boolean isEmpty() {
return top == -1;
}
// 入栈-push
public void push(int value) {
// 先判断是否栈满
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
// 出栈-pop
public int pop() {
// 先判断是否栈空
if (isEmpty()) {
// 抛出异常
throw new RuntimeException("栈空,没有数据");
}
int value = stack[top];
top--;
return value;
}
// 返回运算符的优先级,优先级是程序员来确定,用数字表示
// 数字越大,则优先级越高
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; // res用于存放计算的结果
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;
}
}
逆波兰计算器
要求:
- 输入一个逆波兰表达式(后缀表达式),使用栈(Stack),计算其结果
- 支持小括号和多位数整数
- 思路分析:
package com.algorithm.stack;
//逆波兰计算器
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//先定义逆波兰表达式
//说明:为了方便,逆波兰表达式的数字和符号使用空格隔开
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";//76
//思路:先将其放入ArrayList中,再将ArrayList传递给一个方法,遍历ArrayList配合栈,完成计算
List<String> list = getListString(suffixExpression);
System.out.println("rpnlist=" + list);
int res = calculate(list);
System.out.println("最终结果为" + res);
}
public static List<String> getListString(String suffixExpression){
//将其进行分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele:
split) {
list.add(ele);
}
return list;
}
public static int calculate(List<String> list){
//创建一个栈
Stack<String> stack = new Stack<String>();
//遍历list
for (String item:
list) {
//使用正则表达式取数
if(item.matches("\\d+")) {//匹配的是多位数
//入栈
stack.push(item);
}else{
//pop出两个数,运算后入栈
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if(item.equals("+")){
res = num1 + num2;
}else if(item.equals("-")){
res = num1 - num2;
}else if(item.equals("*")){
res = num1 * num2;
}else if(item.equals("/")){
res = num1 / num2;
}else{
throw new RuntimeException("运算符有误");
}
stack.push(""+res);
}
}
return Integer.parseInt(stack.pop());
}
}
中缀表达式转为后缀表达式
具体步骤
- 初始化两个栈:运算符栈s1和储存中间结果的栈s2
- 从左至右扫描中缀表达式
- 遇到操作数时,将其压s2
- 遇到运算符时,比较其与s1栈顶运算符的优先级
- 如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈
- 否则,若优先级比栈顶运算符的高,也将运算符压入s1
- 否则,将s1栈顶的运算符弹出并压入到s2中,再次转到(4-1)与s1中新的栈顶运算符进行比较
- 遇到括号时:
- 如果是左括号“(”,则直接压入s1
- 如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一堆括号丢弃
- 重复步骤2至5,知道表达式的最右边
- 将s1中剩余的运算符依次弹出并压入s2
- 依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式
代码实现
package com.algorithm.stack;
//逆波兰计算器
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//完成一个中缀表达式转成后缀表达式的功能
//说明
//1. 1+((2+3)*4)-5 => 1 2 3 + 4 * + 5 -
//2.因为直接对str进行操作不方便,因此,先将其转换成对应的List
//3.将得到的中缀表达式对应的List=>后缀表达式对应的List
String expression = "1+((2+3)*4)-5";
List<String> infixExpressionList = toIndexExpressionList(expression);
System.out.println(infixExpressionList);
List<String> suffixExpression = parseSuffixExpressionList(infixExpressionList);
System.out.println(suffixExpression);
//先定义逆波兰表达式
//说明:为了方便,逆波兰表达式的数字和符号使用空格隔开
// String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";//76
//思路:先将其放入ArrayList中,再将ArrayList传递给一个方法,遍历ArrayList配合栈,完成计算
// List<String> list = getListString(suffixExpression);
// System.out.println("rpnlist=" + list);
// int res = calculate(list);
int res = calculate(suffixExpression);
System.out.println("最终结果为" + res);
}
public static List<String> getListString(String suffixExpression){
//将其进行分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String ele:
split) {
list.add(ele);
}
return list;
}
public static List<String> toIndexExpressionList(String s){
//定义一个List存放中缀表达式对应的内容
List<String> ls = new ArrayList<String>();
char c;//遍历到的字符
String str;//多位数拼接
for(int i = 0 ; i < s.length(); ){
//非数字直接加入到ls中
if((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57){
ls.add("" + c);
i++;
}else {//数字
str = "";
while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
str += c;
i++;
}
ls.add(str);
}
}
return ls;
}
public static List<String> parseSuffixExpressionList(List<String> ls){
//定义两个栈
Stack<String> s1 = new Stack<String>();
//说明:因为s2这个栈,在整个转换过程中,没有pop操作,而且后面还需要逆序输出
//比较麻烦,这里直接使用List<String> s2
List<String> s2 = new ArrayList<String>();
//遍历ls
for (String item:
ls) {
//如果是一个数,直接加入s2
if(item.matches("\\d+")){
s2.add(item);
}else if(item.equals("(")){
s1.push(item);
}else if(item.equals(")")){
while(!s1.peek().equals("(")){
s2.add(s1.pop());
}
s1.pop();//消除括号
}else {
//缺少一个比较运算符优先级高低的方法
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
s2.add(s1.pop());
}
//还需要将item压入栈
s1.push(item);
}
}
//将s1中剩余的运算符依次弹出并加入s2
while(!s1.isEmpty()){
s2.add(s1.pop());
}
return s2;
}
public static int calculate(List<String> list){
//创建一个栈
Stack<String> stack = new Stack<String>();
//遍历list
for (String item:
list) {
//使用正则表达式取数
if(item.matches("\\d+")) {//匹配的是多位数
//入栈
stack.push(item);
}else{
//pop出两个数,运算后入栈
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if(item.equals("+")){
res = num1 + num2;
}else if(item.equals("-")){
res = num1 - num2;
}else if(item.equals("*")){
res = num1 * num2;
}else if(item.equals("/")){
res = num1 / num2;
}else{
throw new RuntimeException("运算符有误");
}
stack.push(""+res);
}
}
return Integer.parseInt(stack.pop());
}
}
//编写一个类Operator可以返回一个运算符对应的优先级
class Operation{
private static int ADD = 1;
private static int SUB = 1;
private static int MUL = 2;
private static int DIV = 2;
public static int getValue(String operation){
int result = 0;
switch (operation){
case "+":
result = ADD;
break;
case "-":
result = SUB;
break;
case "*":
result = MUL;
break;
case "/":
result = DIV;
break;
default:
System.out.println("操作符有误");
}
return result;
}
}
逆波兰计算器完整版
功能包括:
- 支持 + - * / ( )
- 多位数,支持小数
- 兼容处理,过滤任何空白字符,包括空格、制表符、换页符
代码实现:
package com.algorithm.stack;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;
public class ReversePolishMultiCalc {
/**
* 匹配 + - * / ( ) 运算符
*/
static final String SYMBOL = "\\+|-|\\*|/|\\(|\\)";
static final String LEFT = "(";
static final String RIGHT = ")";
static final String ADD = "+";
static final String MINUS= "-";
static final String TIMES = "*";
static final String DIVISION = "/";
/**
* 加减 + -
*/
static final int LEVEL_01 = 1;
/**
* 乘除 * /
*/
static final int LEVEL_02 = 2;
/**
* 括号
*/
static final int LEVEL_HIGH = Integer.MAX_VALUE;
static Stack<String> stack = new Stack<>();
static List<String> data = Collections.synchronizedList(new ArrayList<String>());
/**
* 去除所有空白符
* @param s
* @return
*/
public static String replaceAllBlank(String s ){
// \\s+ 匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v]
return s.replaceAll("\\s+","");
}
/**
* 判断是不是 int double long float
* @param s
* @return
*/
public static boolean isNumber(String s){
Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
return pattern.matcher(s).matches();
}
/**
* 判断是不是运算符
* @param s
* @return
*/
public static boolean isSymbol(String s){
return s.matches(SYMBOL);
}
/**
* 匹配运算等级
* @param s
* @return
*/
public static int calcLevel(String s){
if("+".equals(s) || "-".equals(s)){
return LEVEL_01;
} else if("*".equals(s) || "/".equals(s)){
return LEVEL_02;
}
return LEVEL_HIGH;
}
/**
* 匹配
* @param s
* @throws Exception
*/
public static List<String> doMatch (String s) throws Exception{
if(s == null || "".equals(s.trim())) throw new RuntimeException("data is empty");
if(!isNumber(s.charAt(0)+"")) throw new RuntimeException("data illeagle,start not with a number");
s = replaceAllBlank(s);
String each;
int start = 0;
for (int i = 0; i < s.length(); i++) {
if(isSymbol(s.charAt(i)+"")){
each = s.charAt(i)+"";
//栈为空,( 操作符,或者操作符优先级大于栈顶优先级 && 操作符优先级不是( )的优先级 及是 ) 不能直接入栈
if(stack.isEmpty() || LEFT.equals(each)
|| ((calcLevel(each) > calcLevel(stack.peek())) && calcLevel(each) < LEVEL_HIGH)){
stack.push(each);
}else if( !stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())){
//栈非空,操作符优先级小于等于栈顶优先级时出栈入列,直到栈为空,或者遇到了(,最后操作符入栈
while (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek()) ){
if(calcLevel(stack.peek()) == LEVEL_HIGH){
break;
}
data.add(stack.pop());
}
stack.push(each);
}else if(RIGHT.equals(each)){
// ) 操作符,依次出栈直到空栈或者遇到了第一个)操作符,此时)出栈
while (!stack.isEmpty() && LEVEL_HIGH >= calcLevel(stack.peek())){
if(LEVEL_HIGH == calcLevel(stack.peek())){
stack.pop();
break;
}
data.add(stack.pop());
}
}
start = i ; //前一个运算符的位置
}else if( i == s.length()-1 || isSymbol(s.charAt(i+1)+"") ){
each = start == 0 ? s.substring(start,i+1) : s.substring(start+1,i+1);
if(isNumber(each)) {
data.add(each);
continue;
}
throw new RuntimeException("data not match number");
}
}
//如果栈里还有元素,此时元素需要依次出栈入列,可以想象栈里剩下栈顶为/,栈底为+,应该依次出战入列,可以直接翻转整个stack添加到队列
Collections.reverse(stack);
data.addAll(new ArrayList<>(stack));
System.out.println(data);
return data;
}
/**
* 计算结果
* @param list
* @return
*/
public static Double doCalc(List<String> list){
Double d = 0d;
if(list == null || list.isEmpty()){
return null;
}
if (list.size() == 1){
System.out.println(list);
d = Double.valueOf(list.get(0));
return d;
}
ArrayList<String> list1 = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
list1.add(list.get(i));
if(isSymbol(list.get(i))){
Double d1 = doTheMath(list.get(i - 2), list.get(i - 1), list.get(i));
list1.remove(i);
list1.remove(i-1);
list1.set(i-2,d1+"");
list1.addAll(list.subList(i+1,list.size()));
break;
}
}
doCalc(list1);
return d;
}
/**
* 运算
* @param s1
* @param s2
* @param symbol
* @return
*/
public static Double doTheMath(String s1,String s2,String symbol){
Double result ;
switch (symbol){
case ADD : result = Double.valueOf(s1) + Double.valueOf(s2); break;
case MINUS : result = Double.valueOf(s1) - Double.valueOf(s2); break;
case TIMES : result = Double.valueOf(s1) * Double.valueOf(s2); break;
case DIVISION : result = Double.valueOf(s1) / Double.valueOf(s2); break;
default : result = null;
}
return result;
}
public static void main(String[] args) {
//String math = "9+(3-1)*3+10/2";
String math = "12.8 + (2 - 3.55)*4+10/5.0";
try {
doCalc(doMatch(math));
} catch (Exception e) {
e.printStackTrace();
}
}
}