package com.xdt.stack;
public class ArrayStackDemo {
public static void main(String[] args) {
//测试
ArrayStack arrayStack = new ArrayStack(5);
arrayStack.push(1);
arrayStack.push(2);
arrayStack.push(3);
arrayStack.push(4);
arrayStack.push(5);
arrayStack.list();
System.out.println("取出:"+arrayStack.pop());
System.out.println("取出:"+arrayStack.pop());
arrayStack.list();
}
}
class ArrayStack{
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈
private int top=-1;//栈顶,初始化为-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;
}
//入栈
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.println("stack["+i+"]="+stack[i]);
}
}
}
用栈实现一个小的计算器
计算49-62的值
package com.xdt.stack;
public class Calculator {
public static void main(String[] args) {
String expression = "70+2*6-2";
//创建两个栈,一个存放数字的,一个存放表达式
ArrayStack2 number = new ArrayStack2(expression.length() + 1);//数栈
ArrayStack2 operStack = new ArrayStack2(expression.length() + 1);//字符栈
int index = 0;//用于扫描字符串
int num1 = 0;
int num2 = 0;
int res = 0;
int oper = 0;
char ch = '0';
String keepNum = "";//拼接多位数
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
if (operStack.isOper(ch)) {//如果是运算符
if (!operStack.isEmpty()) {//如果不为空
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
num1 = number.pop();
num2 = number.pop();
oper = operStack.pop();
res = number.cal(num2, num1, (char) oper);//将计算的结果放入数据栈
number.push(res);
operStack.push(ch);
} else {
operStack.push(ch);
}
} else {
//为空
operStack.push(ch);
}
} else {
//数字入数栈
keepNum+=ch;
if (index==expression.length()-1){
number.push(Integer.parseInt(keepNum));
}else {
if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))){
number.push(Integer.parseInt(keepNum));
keepNum="";
}
}
}
index++;
if (index == expression.length()) {//遍历完毕
break;
}
}
while (!operStack.isEmpty()) {
num1 = number.pop();
num2 = number.pop();
oper = operStack.pop();
res = number.cal(num2, num1, (char) oper);
number.push(res);//将计算的结果放入数据栈
}
number.list();
}
}
class ArrayStack2 {
private int maxSize;//栈的大小
private int[] stack;//数组模拟栈
private int top = -1;//栈顶,初始化为-1,无数据
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//查看栈顶
public int peek() {
return stack[top];
}
//栈满
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.println("stack[" + i + "]=" + stack[i]);
}
}
//返回运算符的优先级,这里采用数字越大优先级越高
public int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
}
if (oper == '-' || oper == '+') {
return 0;
}
return -1;//运算符错误。目前只适配加减乘除
}
//判断是不是一个运算符
public boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
//计算方法
public int cal(int num1, int num2, char oper) {
int res = 0;//计算的结果
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
}
return res;
}
}
结果等于24
使用逆波兰后缀表达式计算
package com.xdt.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//先定义一个逆波兰表达式
//(3+4)x5-6 > 3 4 + 5 x 6 -
//为了方便,使用空格隔开
String suffixExpression="3 4 + 5 x 6 -";
List<String> listString = getListString(suffixExpression);
System.out.println(calculate(listString));
}
//将逆波兰表达式,依次放入arraylist
public static List<String> getListString(String suffixExpression){
String[] s = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String s1 : s) {
list.add(s1);
}
return list;
}
//计算
public static int calculate(List<String> list){
Stack<String> stack = new Stack<>();
for (String s : list) {
//正则判断
if (s.matches("\\d+")){//匹配是多位数
stack.push(s);
}else {
int num2=Integer.parseInt(stack.pop());
int num1=Integer.parseInt(stack.pop());
int res=0;
if (s.equals("+")) {
res=num1+num2;
}else if (s.equals("-")){
res=num1-num2;
}else if (s.equals("x")){
res=num1*num2;
}else if (s.equals("/")){
res=num1/num2;
}
stack.push(res+"");
}
}
return Integer.parseInt(stack.pop());
}
}
中缀表达式转换逆波兰表达式
package com.xdt.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
String expression = "1+((2+3)*4)-5";
List<String> strings = toInfixExpressionList(expression);
List<String> strings1 = parseSuffixExpressionList(strings);
System.out.println(strings1);
//先定义一个逆波兰表达式
//(3+4)x5-6 > 3 4 + 5 x 6 -
//为了方便,使用空格隔开
/*String suffixExpression = "3 4 + 5 x 6 -";
List<String> listString = getListString(suffixExpression);
System.out.println(calculate(listString));*/
}
//将逆波兰表达式,依次放入arraylist
public static List<String> getListString(String suffixExpression) {
String[] s = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
for (String s1 : s) {
list.add(s1);
}
return list;
}
//转化后缀表达式
public static List<String> parseSuffixExpressionList(List<String> ls) {
//定义两个栈
Stack<String> s1 = new Stack<String>();//符号栈
//因为s2这个栈在整个转换过程中没有pop操作,而且后面还需要逆序输出太麻烦了,于是这里采用list
List<String> s2 = new ArrayList<String>();//存储中间结果的栈
//遍历
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栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较。
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
s2.add(s1.pop());
}
s1.push(item);
}
}
//将s1中剩余的运算符依次弹出并加s2
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;
}
//将中缀表达式转成对应的List
public static List<String> toInfixExpressionList(String s) {
List<String> ls = new ArrayList<String>();
int i = 0;//用于遍历
String str;//对多位数拼接
char c;//放字符
do {
//如果是一个非数字,我们需要加入到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);
}
} while (i < s.length());
return ls;
}
//计算
public static int calculate(List<String> list) {
Stack<String> stack = new Stack<>();
for (String s : list) {
//正则判断
if (s.matches("\\d+")) {//匹配是多位数
stack.push(s);
} else {
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (s.equals("+")) {
res = num1 + num2;
} else if (s.equals("-")) {
res = num1 - num2;
} else if (s.equals("x")) {
res = num1 * num2;
} else if (s.equals("/")) {
res = num1 / num2;
}
stack.push(res + "");
}
}
return Integer.parseInt(stack.pop());
}
}
//返回运算符对应的优先级
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("不操作该运算符!");
break;
}
return result;
}
}