1、栈的一个实际需求
栈的介绍
栈的应用场景
2、栈的快速入门
代码实现
import java.util.Stack;
//演示栈Stack的基本使用
public class TestStack {
public static void main(String[] args) {
Stack<String> stack = new Stack();
// 入栈
stack.add("jack");
stack.add("tom");
stack.add("smith");
// 出栈
// smith, tom , jack
while (stack.size() > 0) {
System.out.println(stack.pop());//pop就是将栈顶的数据取出
}
}
}
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
//测试一下ArrayStack 是否正确
//先创建一个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]);
}
}
}
数组建栈 - - 双端栈
public class TestArrayStackDoubleEnd {
public static void main(String[] args) {
ArrayStackDoubleEnd<Integer> stack=new ArrayStackDoubleEnd<>();
System.out.println(stack);
for(int i=1;i<=5;i++){
stack.pushLeft(i);
}
for(int i=1;i<=6;i++){
stack.pushRight(i);
}
for(int i=13;i<=20;i++){
stack.push(i);
}
System.out.println(stack);
System.out.println();
}
}
class ArrayStackDoubleEnd<E> extends Stack<E> {
//双端栈由于有左右端,难以使用顺序栈来进行操作,便重新定义:
//创建左端和右端,在数组上进行操作,初始化左端为-1,右端为数组长度:
private static final int DEFAULT_SIZE=10;
private E[] data;
private int leftTop;
private int rightTop;
public ArrayStackDoubleEnd(){
this(DEFAULT_SIZE);
}
public ArrayStackDoubleEnd(int capacity){
data=(E[])(new Object[capacity]);
leftTop=-1;
rightTop=data.length;
}
//获取栈中元素的方法,左栈为lefttop+1,右栈为length-righttop,:
//获取左栈中有效元素个数
public int getLeftSize(){
return leftTop+1;
}
//获取右栈中有效元素个数
public int getRightSize(){
return data.length-rightTop;
}
//获取栈中所有元素的个数
public int getSize() {
return getLeftSize()+getRightSize();
}
//---------判空操作:只是比判断一次要麻烦一些。-----
//判断左栈是否为空
public boolean isLeftEmpty(){
return leftTop==-1;
}
//判断右栈是否为空
public boolean isRightEmpty(){
return rightTop==data.length;
}
//判断栈是否为空
@Override
public boolean isEmpty() {
return isLeftEmpty()&&isRightEmpty();
}
//---------------------------------------------------
//进栈操作同顺序表:只不过有左右进栈的区别,
// 同时判断元素个数是否需要扩容(扩容时左栈元素直接从新栈的左边开始复制,右栈元素从新栈右边开始复制)
//在左栈进栈
public void pushLeft(E e){
//满了扩容
if(leftTop+1==rightTop){
resize(2*data.length);
}
leftTop++;
data[leftTop]=e;
}
//在右栈进栈
public void pushRight(E e){
if(rightTop-1==leftTop){
resize(2*data.length);
}
rightTop--;
data[rightTop]=e;
}
/**
* 扩容
* @param newLen
*/
private void resize(int newLen){
E[] newData=(E[])(new Object[newLen]);
//扩容和缩容时左边的复制
for(int i=0;i<=leftTop;i++){
newData[i]=data[i];
}
//扩容时右边的复制
if(newData.length>data.length){
for(int i=rightTop;i<data.length;i++){
newData[i+data.length]=data[i];
}
rightTop=rightTop+data.length;
}else{//缩容时右边的复制
for(int i=rightTop;i<data.length;i++){
newData[i-newData.length]=data[i];
}
rightTop=rightTop-newData.length;
}
data=newData;
}
//--------进栈一个元素,根据左右栈的元素个数比较判断进左栈还是右栈:------------
//进栈元素e
@Override
public E push(E e) {
if(getLeftSize()<=getRightSize()){
pushLeft(e);
}else{
pushRight(e);
}
return e;
}
//出栈:左栈弹栈,首先判空,不为空则弹栈,返回该元素。右栈相同,直接进栈则判断左右栈的有效元素个数。
public E popLeft(){
if(isLeftEmpty()){
throw new IllegalArgumentException("左栈为空");
}
E ret=data[leftTop--];
if(getSize()<=data.length/4&&data.length/2>10){
resize(data.length/2);
}
return ret;
}
public E popRight(){
if(isRightEmpty()){
throw new IllegalArgumentException("右栈为空");
}
E ret=data[rightTop++];
if(getSize()<=data.length/4&&data.length/2>=10){
resize(data.length/2);
}
return ret;
}
@Override
public E pop() {
if(getLeftSize()>=getRightSize()){
return popLeft();
}else{
return popRight();
}
}
//查看栈顶元素,同理,有两个栈顶,需要左右区别。
public E peekLeft(){
if(isLeftEmpty()){
throw new IllegalArgumentException("左栈为空");
}
return data[leftTop];
}
public E peekRight(){
if(isRightEmpty()){
throw new IllegalArgumentException("右栈为空");
}
return data[rightTop];
}
@Override
public E peek() {
if(getLeftSize()>=getRightSize()){
return peekLeft();
}else{
return peekRight();
}
}
//清空,创建新数组,给左右栈顶重新赋值即可。
@Override
public void clear() {
data= (E[]) new Object[DEFAULT_SIZE];
leftTop=-1;
rightTop=data.length;
}
//toString()字符串输出,需要先输出左栈判断左栈是否为空,然后再输出右栈元素并且判断右栈是否为空,略微有些麻烦。不过道理是相同的
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(String.format("ArrayStackDoubleEnd: %d/%d\n",getSize(),data.length));
if(isLeftEmpty()){
sb.append("left :bottom [] top");
}else{
sb.append("left :bottom [");
for(int i=0;i<=leftTop;i++){
sb.append(data[i]);
if(i==leftTop){
sb.append("] top");
}else{
sb.append(',');
}
}
}
sb.append('\n');
if(isRightEmpty()){
sb.append("right:top [] bootom\n");
}else {
sb.append("right:top [");
for(int i=rightTop;i<data.length;i++){
sb.append(data[i]);
if(i==data.length-1){
sb.append("] bottom");
}else{
sb.append(',');
}
}
}
return sb.toString();
}
@Override
public Iterator<E> iterator() {
return null;
}
}
课堂练习,将上面的程序改成使用链表来模拟栈.
class LLNode {
private int data; //数据域
private LLNode next; //指针域
public LLNode(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LLNode getNext() {
return next;
}
public void setNext(LLNode next) {
this.next = next;
}
}
public class TestLinklistStackDemo {
private LLNode top;
private int length = 0;
public TestLinklistStackDemo() {
this.top = null;
}
//判断栈中是否有元素
public boolean isEmpty() {
if(top == null) {
return true;
}else {
return false;
}
}
//入栈:将数据压入栈
public void push(int data) {
LLNode newNode = new LLNode(data);
if(isEmpty()) {
top = newNode;
}else {
newNode.setNext(top);
top = newNode;
}
length++;
}
//出栈:删除并返回最后一个插入栈的元素
public int pop() {
if(isEmpty()) {
System.out.println("栈为空");
return 0;
}else {
int data = top.getData();
top = top.getNext();
length--;
return data;
}
}
//获取栈顶的元素,但不出栈
public int top() {
if(isEmpty()) {
System.out.println("栈为空");
return 0;
}else {
return top.getData();
}
}
//返回栈中元素的个数
public int size() {
return length;
}
//删除栈
public void deteleStack() {
top = null;
}
public static void main(String[] args) {
TestLinklistStackDemo stack = new TestLinklistStackDemo();
stack.push(0);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop()); // 4
System.out.println(stack.top()); //3
System.out.println(stack.size()); // 4
System.out.println(stack.isEmpty()); //false
}
}
加上想一想,用双向链表来模拟双端栈有没有意义
3、计算器(中缀表达式计算)
代码实现
package com.atguigu.stack;
public class Calculator {
public static void main(String[] args) {
//根据前面老师思路,完成表达式的运算
String expression = "7*2*2-5+1-5+3-4"; // 15//如何处理多位数的问题?
//创建两个栈,数栈,一个符号栈
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)) {//如果是运算符
//判断当前的符号栈是否为空
if(!operStack.isEmpty()) {
//如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符,就需要从数栈中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 {
//如果为空直接入符号栈..
operStack.push(ch); // 1 + 3
}
} else { //如果是数,则直接入数栈
//numStack.push(ch - 48); //? "1+3" '1' => 1
//分析思路
//1. 当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
//2. 在处理数,需要向expression的表达式的index 后再看一位,如果是数就进行扫描,如果是符号才入栈
//3. 因此我们需要定义一个变量 字符串,用于拼接
//处理多位数
keepNum += ch;
//如果ch已经是expression的最后一位,就直接入栈
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
}else{
//判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈
//注意是看后一位,不是index++
if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
//如果后一位是运算符,则入栈 keepNum = "1" 或者 "123"
numStack.push(Integer.parseInt(keepNum));
//重要的!!!!!!, keepNum清空
keepNum = "";
}
}
}
//让index + 1, 并判断是否扫描到expression最后.
index++;
if (index >= expression.length()) {
break;
}
}
//当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行.
while(true) {
//如果符号栈为空,则计算到最后的结果, 数栈中只有一个数字【结果】
if(operStack.isEmpty()) {
break;
}
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;// 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 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; // 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;
}
}
课后练习题-----加入小括号.
public class CalculatorStackPlus1 {
private Stack<Character> optr = new Stack<Character>();// 操作符栈
private Stack<Float> opnd = new Stack<Float>();// 操作数栈
private final Character END_Character = '#';// 输入表达式的结束字符
public final int ADD = 0, SUB = 1, MUL = 2, DIV = 3, MOD = 4, POW = 5, FAC = 6, L_P = 7, R_P = 8, EOF = 9;
public final char[][] PRI = {//运算符优先等级 [栈顶]'levle'[当前]
// |----------------当前运算符----------------|
// + - * / % ^ ! ( ) #(结束字符)
/* + */ {'>','>','<','<','<','<','<','<','>','>'},
/* - */ {'>','>','<','<','<','<','<','<','>','>'},
/* 栈 * */ {'>','>','>','>','>','<','<','<','>','>'},
/* 顶 / */ {'>','>','>','>','>','<','<','<','>','>'},
/* 运 % */ {'>','>','>','>','>','<','<','<','>','>'},
/* 算 ^ */ {'>','>','>','>','>','>','<','<','>','>'},
/* 符 ! */ {'>','>','>','>','>','>','>',' ','>','>'},
/* ( */ {'<','<','<','<','<','<','<','<','=',' '},
/* ) */ {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},
/* # */ {'<','<','<','<','<','<','<','<',' ','='}
};
/**
* 中缀表达式计算,程序核心部分
* @param expression
* 输入的有效中缀表达式
* @return
*/
public float calcExpression(String expression) throws Exception {
// 初始时操作符栈压入开始标识符,与结束字符对应
optr.push(END_Character);
// 剔除表达式中的空格
expression = removeSpace(expression);
int i = 0;// 表示读取表示式的位置
while (!optr.empty()) {
char currenSymbol = expression.charAt(i);// 当前扫描到的表达式符号
if (Character.isDigit(currenSymbol)) {
i = readNumber(expression, i, opnd);// 读入(可能多位的)操作数
} else {
switch (orderBetween(optr.peek(), currenSymbol)) {
case '>':// 栈顶运算符的优先级大于当前运算符,则1.取出操作符栈顶运算符,2.取出数据栈中的一个或多个数据(取决于运算符的类型),3.运算并把结果压入数据栈中
char op = optr.pop();// 取出栈顶操作符
Calculator1 ca = new Calculator1();// 基本计算操作对象
if ('!' == op) {// 一元运算符的计算
float number = opnd.pop();// 取出操作数栈顶数值
System.out.println("计算过程:" + "[" + number + "]" + "" + op + "=" + "[" +ca.calcu(number, op) +"]" );
opnd.push(ca.calcu(number, op));// 计算并将结果入栈
} else {// 二元运算符的计算
float number2 = opnd.pop();// 取出操作数栈顶数值
float number1 = opnd.pop();// 取出操作数栈顶数值
System.out.println("计算过程:" + "[" + number1 + "]" + "" + op + "" + "[" + number2 + "]" + "=" + "[" +ca.calcu(number1, op, number2) + "]");
opnd.push(ca.calcu(number1, op, number2));// 计算并将结果入栈
}
break;
case '<':// 栈顶运算符的优先级小于当前运算符,计算推迟,当前运算符入栈
optr.push(currenSymbol);
i++;
break;
case '=':// 栈顶运算符的优先级等于当前运算符,脱括号并接收下一个字符
optr.pop();
i++;
break;
case ' ':
throw new Exception("ERROR");
}
}
}
return opnd.pop();// 操作数栈的最后一个元素即为需要的结果
}
/**
* 将char型的数字字符转为浮点型数据
* @param ch
* @return
*/
private float CharToFloat(char ch) {
return Float.valueOf("" + ch);
}
/**
* 将起始为i的子串解析为数值,并存入操作数栈中
* @param expression 表达式
* @param i 开始解析的位置
* @param stk 将解析完毕的数值存入此栈中
* @return 该数值解析完毕后,返回表达式需要解析的下一个位置
* @throws Exception 解析错误
*/
private int readNumber(String expression, int i, Stack<Float> stk) throws Exception {
stk.push(CharToFloat(expression.charAt(i++)));// 当前数位对应的数值进栈
char op = expression.charAt(i); // 读取下一个字符
while (Character.isDigit(op)) {// 只要后续还有紧邻的数字
stk.push(stk.pop() * 10 + CharToFloat(op));// 弹出原操作数并追加新数位后,新数值重新入栈
op = expression.charAt(++i);// 下一个字符
}
if ('.' != op)
return i;// 如果最后一个数字后面不是小数点,说明解析完成,则返回当前位置
op = expression.charAt(++i);
float fraction = 1;
while (Character.isDigit(op)) {
stk.push(stk.pop() + CharToFloat(op) * (fraction /= 10));
op = expression.charAt(++i);
}
if ('.' == op)
throw new Exception("ERROR");// 如果还有小数点则错误
return i;// 返回当前解析字符的位置
}
/**
* 根据运算符获取在优先级表中的秩(RANK)
* @param op
* @return
* @throws Exception
*/
private int getOperRank(char op) throws Exception {
switch (op) {
case '+':
return ADD;
case '-':
return SUB;
case '*':
return MUL;
case '/':
return DIV;
case '%':
return MOD;
case '^':
return POW;
case '!':
return FAC;
case '(':
return L_P;
case ')':
return R_P;
case '#':
return EOF;
default:
throw new Exception("ERROR");
}
}
/**
* 比较栈顶和当前字符的优先级
* @param peekOptr 栈顶运算符
* @param currenOptr 当前扫描到的运算符
* @return 优先级表中的数据项
* @throws Exception
*/
private Character orderBetween(Character peekOptr, char currenOptr) throws Exception {
return PRI[getOperRank(peekOptr)][getOperRank(currenOptr)];
}
/**
* 剔除字符串之间的空格
* @param str
* @return
*/
public String removeSpace(String str) {
char[] chs = str.toCharArray();
StringBuffer newStr = new StringBuffer();
int i = 0;
while (i < str.length()) {
if (' ' != chs[i]) {
newStr.append(chs[i]);
}
i++;
}
return newStr.toString();
}
// test
public static void main(String[] args) throws Exception {
CalculatorStackPlus1 sc = new CalculatorStackPlus1();
String s = "(1 + 2^3!-4)*(5!-(6-( 7-(89-0!))))#";// 2013
System.out.println("结果:" + sc.calcExpression(s));
}
}
class Calculator1 {
/**
* 一元运算符
*/
public float calcu(float n, char op) throws Exception {
return fact(n);// 这里只有阶乘一个一元运算符
}
/**
* 二元运算符
*
* @param a
* 操作数1
* @param op
* 操作符
* @param b
* 操作数2
* @return 结果浮点型
* @throws Exception
*/
public float calcu(float a, char op, float b) throws Exception {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return div(a, b);
case '%':
return mod(a, b);
case '^':
return (float) Math.pow(a, b);
default:
throw new Exception("ERROR");
}
}
private float div(float a, float b) throws Exception {
if (b == 0)
throw new Exception("除数不能为0!");
return a / b;
}
// 取余
private float mod(float a, float b) throws Exception {
if (b == 0)
throw new Exception("除数不能为0!");
return a % b;
}
// 阶乘 n!(n<=20)
private float fact(float n) throws Exception {
if (n < 0)
throw new Exception("阶乘运算数不能为负数!");
if (n > 34)
throw new Exception("阶乘数不能超过34,否则越界!");// 可以考虑改进以使计算更大数值的阶乘
if (n == 0)
return 1;// 0!=1
int num = (int) n;
if (num == n) {// n为整数
float result = 1;
while (num > 0) {
result *= num--;
}
return result;
} else
throw new Exception("阶乘运算数必须为整数!");
}
}
4、前缀 中缀 后缀 表达式理论规则
波澜—(提神醒脑)
5、计算器(后缀计算)–逆波兰
代码实现
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* 逆波兰计算器
*/
public class PolandNotation {
public static void main(String[] args) {
//先定义给逆波兰表达式
//(30+4)×5-6 => 30 4 + 5 × 6 - => 164
// 4 * 5 - 8 + 60 + 8 / 2 => 4 5 * 8 - 60 + 8 2 / +
//测试
//说明为了方便,逆波兰表达式 的数字和符号使用空格隔开
//String suffixExpression = "30 4 + 5 * 6 -";
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +"; // 76
//思路
//1. 先将 "3 4 + 5 × 6 - " => 放到ArrayList中
//2. 将 ArrayList 传递给一个方法,遍历 ArrayList 配合栈 完成计算
List<String> list = getListString(suffixExpression);
System.out.println("rpnList=" + list);
int res = calculate(list);
System.out.println("计算的结果是=" + res);
}
//将一个逆波兰表达式, 依次将数据和运算符 放入到 ArrayList中
public static List<String> getListString(String suffixExpression) {
//将 suffixExpression 分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for(String ele: split) {
list.add(ele);
}
return list;
}
//完成对逆波兰表达式的运算
/*
* 1)从左至右扫描,将3和4压入堆栈;
2)遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
3)将5入栈;
4)接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
5)将6入栈;
6)最后是-运算符,计算出35-6的值,即29,由此得出最终结果
*/
public static int calculate(List<String> ls) {
// 创建给栈, 只需要一个栈即可
Stack<String> stack = new Stack<String>();
// 遍历 ls
for (String item : ls) {
// 这里使用正则表达式来取出数
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("运算符有误");
}
//把res 入栈
stack.push("" + res);
}
}
//最后留在stack中的数据是运算结果
return Integer.parseInt(stack.pop());
}
}
6、中缀转后缀(理论+实操)
代码实现
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation2 {
public static void main(String[] args) {
//完成将一个中缀表达式转成后缀表达式的功能
//说明
//1. 1+((2+3)×4)-5 => 转成 1 2 3 + 4 × + 5 –
//2. 因为直接对str 进行操作,不方便,因此 先将 "1+((2+3)×4)-5" =》 中缀的表达式对应的List
// 即 "1+((2+3)×4)-5" => ArrayList [1,+,(,(,2,+,3,),*,4,),-,5]
//3. 将得到的中缀表达式对应的List => 后缀表达式对应的List
// 即 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–]
String expression = "1+((2+3)*4)-5";//注意表达式
List<String> infixExpressionList = toInfixExpressionList(expression);
System.out.println("中缀表达式对应的List=" + infixExpressionList); // ArrayList [1,+,(,(,2,+,3,),*,4,),-,5]
List<String> suffixExpreesionList = parseSuffixExpreesionList(infixExpressionList);
System.out.println("后缀表达式对应的List" + suffixExpreesionList); //ArrayList [1,2,3,+,4,*,+,5,–]
System.out.printf("expression=%d", calculate(suffixExpreesionList)); // ?
/*
//先定义给逆波兰表达式
//(30+4)×5-6 => 30 4 + 5 × 6 - => 164
// 4 * 5 - 8 + 60 + 8 / 2 => 4 5 * 8 - 60 + 8 2 / +
//测试
//说明为了方便,逆波兰表达式 的数字和符号使用空格隔开
//String suffixExpression = "30 4 + 5 * 6 -";
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +"; // 76
//思路
//1. 先将 "3 4 + 5 × 6 - " => 放到ArrayList中
//2. 将 ArrayList 传递给一个方法,遍历 ArrayList 配合栈 完成计算
List<String> list = getListString(suffixExpression);
System.out.println("rpnList=" + list);
int res = calculate(list);
System.out.println("计算的结果是=" + res);
*/
}
//即 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–]
//方法:将得到的中缀表达式对应的List => 后缀表达式对应的List
public static List<String> parseSuffixExpreesionList(List<String> ls) {
//定义两个栈
Stack<String> s1 = new Stack<String>(); // 符号栈
//说明:因为s2 这个栈,在整个转换过程中,没有pop操作,而且后面我们还需要逆序输出
//因此比较麻烦,这里我们就不用 Stack<String> 直接使用 List<String> s2
//Stack<String> s2 = new Stack<String>(); // 储存中间结果的栈s2
List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2
//遍历ls
for(String item: ls) {
//如果是一个数,加入s2
if(item.matches("\\d+")) {
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
//如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
while(!s1.peek().equals("(")) {
s2.add(s1.pop());
}
s1.pop();//!!! 将 ( 弹出 s1栈, 消除小括号
} else {
//当item的优先级小于等于s1栈顶运算符, 将s1栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较
//问题:我们缺少一个比较优先级高低的方法
while(s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item) ) {
s2.add(s1.pop());
}
//还需要将item压入栈
s1.push(item);
}
}
//将s1中剩余的运算符依次弹出并加入s2
while(s1.size() != 0) {
s2.add(s1.pop());
}
return s2; //注意因为是存放到List, 因此按顺序输出就是对应的后缀表达式对应的List
}
//方法:将 中缀表达式转成对应的List
// s="1+((2+3)×4)-5";
public static List<String> toInfixExpressionList(String s) {
//定义一个List,存放中缀表达式 对应的内容
List<String> ls = new ArrayList<String>();
int i = 0; //这时是一个指针,用于遍历 中缀表达式字符串
String str; // 对多位数的拼接
char c; // 每遍历到一个字符,就放入到c
do {
//如果c是一个非数字,我需要加入到ls
if((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57) {
ls.add("" + c);
i++; //i需要后移
} else { //如果是一个数,需要考虑多位数
str = ""; //先将str 置成"" '0'[48]->'9'[57]
while(i < s.length() && (c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) {
str += c;//拼接
i++;
}
ls.add(str);
}
}while(i < s.length());
return ls;//返回
}
//将一个逆波兰表达式, 依次将数据和运算符 放入到 ArrayList中
public static List<String> getListString(String suffixExpression) {
//将 suffixExpression 分割
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for(String ele: split) {
list.add(ele);
}
return list;
}
//完成对逆波兰表达式的运算
/*
* 1)从左至右扫描,将3和4压入堆栈;
2)遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
3)将5入栈;
4)接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
5)将6入栈;
6)最后是-运算符,计算出35-6的值,即29,由此得出最终结果
*/
public static int calculate(List<String> ls) {
// 创建给栈, 只需要一个栈即可
Stack<String> stack = new Stack<String>();
// 遍历 ls
for (String item : ls) {
// 这里使用正则表达式来取出数
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("运算符有误");
}
//把res 入栈
stack.push("" + res);
}
}
//最后留在stack中的数据是运算结果
return Integer.parseInt(stack.pop());
}
}
//编写一个类 Operation 可以返回一个运算符 对应的优先级
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("不存在该运算符" + operation);
break;
}
return result;
}
}
7、完整版逆波兰计算器
----中缀转后缀,后缀计算
package DataStructures.a04_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";
// System.out.println(math);
// try {
// doCalc(doMatch(math));
// } catch (Exception e) {
// e.printStackTrace();
// }
String math1 = "12.8 + (2 - 3.55)*4+10/5.0";
System.out.println(math1);
try {
doCalc(doMatch(math1));
} catch (Exception e) {
e.printStackTrace();
}
}
}
8、栈的其他应用举例
9、栈和递归的爱恨情仇
我写的递归文章https://blog.csdn.net/weixin_46344594/article/details/119837070
(1)递归的定义
- 若一个对象部分的包含它自己,或者用它自己给它自己定义,则称这个对象是递归的。
- 若一个过程直接地或间接地调用自己,则称这个过程是递归的过程。
我写的汉诺塔代码https://blog.csdn.net/weixin_46344594/article/details/116519601
10、总结
- 定义
限定只能在表的一端(栈顶)进行插入和删除运算的线性表 - 逻辑结构
与线性表相同,仍是一对一关系 - 存储结构
用顺序栈或链栈均可,以顺序栈更常见 - 运算规则
只能在栈顶运算,且访问节点时依照后进先出(LIFO)原则 - 实现方式
关键是编写入栈和出栈函数,具体依顺序栈还是链栈不同