棧和隊列是Java中非常重要的數據結構,它們被廣泛應用于許多程序的實現中。下面我們通過幾個例子來學習一下棧和隊列在Java中的應用。
例1:用棧進行表達式求值
public static double evaluate(String expression) { Stack<Double> operands = new Stack<>(); Stack<Character> operators = new Stack<>(); expression = expression.replaceAll(" ", ""); int i = 0; while (i < expression.length()) { char c = expression.charAt(i); if (Character.isDigit(c)) { StringBuilder sb = new StringBuilder(); while (i < expression.length() && (Character.isDigit(expression.charAt(i)) || expression.charAt(i) == '.')) { sb.append(expression.charAt(i)); i++; } operands.push(Double.parseDouble(sb.toString())); continue; } if (c == '(') { operators.push(c); } else if (c == ')') { while (operators.peek() != '(') { double result = applyOperator(operands.pop(), operands.pop(), operators.pop()); operands.push(result); } operators.pop(); } else { while (!operators.isEmpty() && precedence(c) <= precedence(operators.peek())) { double result = applyOperator(operands.pop(), operands.pop(), operators.pop()); operands.push(result); } operators.push(c); } i++; } while (!operators.isEmpty()) { double result = applyOperator(operands.pop(), operands.pop(), operators.pop()); operands.push(result); } return operands.pop(); } private static int precedence(char operator) { switch (operator) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } throw new IllegalArgumentException("Unknown operator: " + operator); } private static double applyOperator(double b, double a, char operator) { switch (operator) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; case '^': return Math.pow(a, b); } throw new IllegalArgumentException("Unknown operator: " + operator); }
例2:用隊列實現二叉樹的層次遍歷
public List<Integer> levelOrderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); result.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } } return result; }
通過以上的例子,我們對Java中的棧和隊列有了一定的了解。我們可以看到,棧和隊列在程序設計中具有重要作用,并且它們的應用場景非常廣泛。
上一篇css中跳轉頁面代碼