資料結構&演算法筆記
  • Introduction
  • 1. Data Structure
  • 1.1 Stack
  • 1.1.1 Stack: Revert String
  • 1.1.2 Stack: Brackets Matching
  • 1.1.3 Stack: Reverse Polish Notation
  • 1.1.4 Stack: Calculattion for Reverse Polish Notation
  • 1.2 Queue
  • 1.2.1 Priority Queue
  • 1.3 Linked List
  • 1.3.1 Linked List - Reorder Function
  • 1.3.2 Ordered Linked List
  • 1.4 Tree
  • 1.4.1 Binary Search Tree
  • 1.4.2 Heap Tree
  • 1.4.3 Red-Black Tree
  • 1.4.3.1 RB Tree Insertion
  • 1.4.3.2 RB Tree Insertion Implementation
  • 1.4.3.3 RB Tree Delete
  • 1.4.3.4 RB Tree Delete Implementation
  • 1.4.4 B-Tree
  • 2. Algorithm
  • 2.1 Sort
  • 2.1.1 Bubble Sort
  • 2.1.2 Selection Sort
  • 2.1.3 Insertion Sort
  • 2.1.4 Merge Sort
  • 2.1.5 Quick Sort
  • 2.1.6 Merge Sort v.s. Quick Sort
  • 2.2 Search
  • 2.2.1 Binary Search
  • 2.3 Dynamic Programming
  • 2.3.1 Fibonacci Series
  • 2.3.2 Find Longest Common Suffix
  • X. Time Complexity Cheat Sheet
Powered by GitBook
On this page

Was this helpful?

1.1.4 Stack: Calculattion for Reverse Polish Notation

Previous1.1.3 Stack: Reverse Polish NotationNext1.2 Queue

Last updated 5 years ago

Was this helpful?

計算後綴表達式求值

  1. 從左到右依序讀取表達式中的字元

  2. 若是運算元, push to stack

  3. 若是運算子, 從stack中pop出兩個資料進行運算, 並把結果push入stack中

  4. 直到表達式結束

原始碼

package idv.carl.datastructures.stack;

/**
 * @author Carl Lu
 */
public class ReversePolishNotationCalculator {

    private final static char ADD = '+';
    private final static char MINUS = '-';
    private final static char MULTIPLY = '*';
    private final static char DIVIDE = '/';

    public int calculate(String rpnExpression) {
        Stack stack = new Stack(20);
        char[] chars = rpnExpression.toCharArray();

        // Step1. Obtain char from input sequentially
        for (char c : chars) {
            /*
             * Step2. Push the element into stack if it's a operand
             * (here we only assume the operand is n, and 0 ≤ n ≤ 9)
             */
            if (c >= '0' && c <= '9') {
                stack.push((int) c - '0');
            }
            /*
             * Step3. If it's a operator, pop two value from stack for calculation, then put the
             * result back to the stack
             */
            else {
                int latter = stack.pop();
                int former = stack.pop();
                int tmp = 0;
                if (c == ADD) {
                    tmp = former + latter;
                } else if (c == MINUS) {
                    tmp = former - latter;
                } else if (c == MULTIPLY) {
                    tmp = former * latter;
                } else if (c == DIVIDE) {
                    tmp = former / latter;
                }
                // Push back to the stack
                stack.push(tmp);
            }
        }
        return stack.pop();
    }

}
點我