自定义栈结构
package cStack;
public class Stack {
private int defaultSize = 10;
protected Object[] objs;
protected int top;
public Stack() {
objs = new Object[10];
top = 0;
}
public boolean isEmpty() {
return top == 0;
}
public boolean isFull() {
return top == defaultSize;
}
public void initStack() {
top = 0;
}
public void push(Object obj) {
if (isFull())
System.out.println("栈满---");
objs[top++] = obj;
}
public Object pop() {
if (isEmpty()) {
System.out.println("栈空-----");
return null;
}
return objs[--top];
}
public Object getTop() {
if (isEmpty()) {
System.out.println("栈空-----");
return null;
}
return objs[top - 1];
}
}
理解
![栈应用--表达式求值 栈应用--表达式求值](/default/index/img?u=aHR0cHM6Ly9waWFuc2hlbi5jb20vaW1hZ2VzLzEzMy82MDMxMWU0ZDM2ZTkwNTBhMzQ5ZWFiY2M2NDM1MDJiZC5wbmc=)
![栈应用--表达式求值 栈应用--表达式求值](/default/index/img?u=aHR0cHM6Ly9waWFuc2hlbi5jb20vaW1hZ2VzLzk3MS8xZDM2YTQzZGYwYWQxYWU1ODkwYmVlOGMyYjdmMDdiYi5wbmc=)
![栈应用--表达式求值 栈应用--表达式求值](/default/index/img?u=aHR0cHM6Ly9waWFuc2hlbi5jb20vaW1hZ2VzLzcxLzg4MzQ5YjEwNzU2MTZhZGUzNGM2NmZmNTJlODZlMTlmLnBuZw==)
java代码实现
package cStack;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class Demo {
private static final Map<Character, Integer> OPS;
private static final char table[][] = {
{ '>', '>', '<', '<', '<', '>', '>' },
{ '>', '>', '<', '<', '<', '>', '>' },
{ '>', '>', '>', '>', '<', '>', '>' },
{ '>', '>', '>', '>', '<', '>', '>' },
{ '<', '<', '<', '<', '<', '=', ' ' },
{ '>', '>', '>', '>', ' ', '>', '>' },
{ '<', '<', '<', '<', '<', ' ', '=' },
};
static {
OPS = new HashMap<>();
OPS.put('+', 0);
OPS.put('-', 1);
OPS.put('*', 2);
OPS.put('/', 3);
OPS.put('(', 4);
OPS.put(')', 5);
OPS.put('#', 6);
}
public static void main(String[] args) {
new Demo().demo3();
}
@Test
public void demo3() {
char[] data = "4-5*6+(1-1*4)#".toCharArray();
Stack numS = new Stack();
Stack optS = new Stack();
optS.push('#');
int i = 0;
while ((char) optS.getTop() != '#' || data[i] != '#') {
char c = data[i];
if (isNum(c)) {
numS.push(c);
i++;
} else {
char top = (char) optS.getTop();
char flag = compareOpt(top, c);
if (flag == '>') {
int result = calculate((char) optS.pop(), new Integer(numS.pop() + ""),
new Integer(numS.pop() + ""));
numS.push(result);
System.out.println(result);
} else if (flag == '=') {
optS.pop();
i++;
} else {
optS.push(c);
i++;
}
}
}
System.out.println(numS.getTop());
}
@Test
public void testmethod() {
double result = calculate('/', 3, 5);
System.out.println(result);
}
private int calculate(char opt, int num1, int num2) {
System.out.print(num2 + " " + opt + " " + num1 +" = ");
switch (opt) {
case '+':
return num2 + num1;
case '-':
return num2 - num1;
case '*':
return num2 * num1;
case '/':
return num2 / num1;
default:
throw new RuntimeException("无法计算");
}
}
private char compareOpt(char top, char c) {
int l = OPS.get(top);
int r = OPS.get(c);
return table[l][r];
}
private boolean isNum(char c) {
return c >= '0' && c <= '9';
}
}