栈用于计算多项表达式思路如下(假设式子为标准的中序表达式如:(5+(6 * 3)-(10 / 2))):
- 建立两个栈(ops, val)用来存储运算符以及数字
- 从左到右遍历式子。
- 遇见“(”,忽略
- 遇见运算符, 压入ops栈中
- 遇见数字,压入val栈中
- 遇见“)”,弹出一个操作符以及两个数字,将两个数字以弹出的运算符运算,运算结果压入val栈中
- 重复以上,直到val栈中只剩下一个数字
实现代码如下:
import edu.princeton.cs.algs4.StdIn;
public class Blog1 {
public static void mian(String[] args) {
Stack<String> ops = new Stack<String>();
Stack<Integer> val = new Stack<Integer>();
while(!StdIn.isEmpty()) {
String s = StdIn.readString();
if(s == "(") ;
else if(s == "+") ops.push(s);
else if(s == "*") ops.push(s);
else if(s == ")") {
String op = ops.pop();
if(op == "+") val.push(val.pop() + val.pop());
else if(op == "*") val.push(val.pop() * val.pop());
}
else val.push(Integer.parseInt(s));
}
System.out.println(val.pop());
}
}
下面是用例中栈的实现:
import java.util.Iterator;
public class Stack<Item> implements Iterable<Item>{
private Node top; //栈顶元素
private int size; //元素数量
private class Node {
Item item;
Node next;
}
public boolean isEmpty() {
return top == null;
}
public int size() {
return size;
}
public void push(Item item) {
Node oldTop = top;
top = new Node();
top.item = item;
top.next = oldTop;
size++;
}
public Item pop() {
Item item = top.item;
top = top.next;
size--;
return item;
}
//以下部分是为了实现foreach打印
public Iterator<Item> iterator() {
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
private Node current = top;
public boolean hasNext() {
return current != null;
}
public void remove() {}
public Item next() {
Item item = current.item;
current = current.next;
return item;
}
}
}