public class Node { int val; Node next; Node(int val) { this.val = val; } }
Stack 实现机制:
public class Stack { Node top; public Node peek() { if (top != null) { return top; } return null; } public Node pop() { if (top == null) return null; else { Node tmp = new Node(top.val); top = top.next; return tmp; } } public void push(Node n) { if (n != null) { n.next = top; top = n; } } }
逆波兰表达式例子:
["1", "2", "+", "3", "*"] -> ((1 + 2) * 3) -> 9
["4", "10", "5", "/", "+"] -> (4 + (10 / 5)) -> 6
我们可以直接用JDK提供的Stack来计算逆波兰表达式的值:
public class Test { public static void main(String[] args) throws IOException { String[] tokens = new String[] { "1", "2", "+", "3", "*" }; System.out.println(compute(tokens)); } public static int compute(String[] tokens) { int returnValue = 0; String operators = "+-*/"; Stack<String> stack = new Stack<String>(); for (String t : tokens) { if (!operators.contains(t)) { stack.push(t); } else { int a = Integer.valueOf(stack.pop()); int b = Integer.valueOf(stack.pop()); switch (t) { case "+": stack.push(String.valueOf(a + b)); break; case "-": stack.push(String.valueOf(b - a)); break; case "*": stack.push(String.valueOf(a * b)); break; case "/": stack.push(String.valueOf(b / a)); break; } } } returnValue = Integer.valueOf(stack.pop()); return returnValue; } }