새소식

인기 검색어

비트교육_단기과정

후위표기법 stack을 사용하여 수식계산

  • -

 

Stack_Num

package week_4;
 
public class Stack_num {
    private int[] arr;
    private int cnt;
 
    public Stack_num(int size) {
        arr = new int[size];
    }
 
    public int pop() {
        if (cnt > 0) {
            return arr[--cnt];
        }
        return -1;
    }
 
    public void push(int value) {
        if (cnt < arr.length) {
            arr[cnt++= value;
        } else {
            System.out.println("여유공간이 없습니다");
        }
    }
 
    public int[] getArr() {
        return arr;
    }
 
    public void setArr(int[] arr) {
        this.arr = arr;
    }
 
}
 
cs

Stack_Operator

package week_4;
 
public class stack_Operator {
    private String[] arr;
    private int cnt;
 
    public stack_Operator(int size) {
        arr = new String[size];
    }
 
    public String pop() {
        if (cnt > 0) {
            return arr[--cnt];
        }
        return null;
    }
 
    public void push(String value) {
        if (cnt < arr.length) {
            arr[cnt++= value;
        } else {
            System.out.println("여유공간이 없습니다");
        }
    }
 
    public String check() {// 스택의 마지막값이 ( true 아니면 false
        if (cnt == 0)
            return "empty";
        return arr[cnt - 1];
    }
 
    public String[] getArr() {
        return arr;
    }
 
    public void setArr(String[] arr) {
        this.arr = arr;
    }
 
    public int getCnt() {
        return cnt;
    }
 
    public void setCnt(int cnt) {
        this.cnt = cnt;
    }
 
}
 
cs

제네릭 미사용

package week_4;
 
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
 
public class StackAlgorithmsExample {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String formula = sc.nextLine().replaceAll(" """);
        ;// 중위 표기법 계산식
        String formula_last = "";// 후위 표기법
        StringTokenizer st01 = new StringTokenizer(formula, "+-()"true);
        StringTokenizer st02 = new StringTokenizer(formula, "+-()"false);
        stack_Operator stack_Operator = new stack_Operator((st01.countTokens() - st02.countTokens())); // 연산자 스택
        while (st01.hasMoreTokens()) {
            String temp = st01.nextToken();
            if (!(temp.equals("+"|| temp.equals("-"|| temp.equals("("|| temp.equals(")"))) {// 피연산자일경우
                formula_last += temp + " "//
            } else {// 연산자일경우
                if (temp.equals("(")) {// ( 일경우 연산자 스택에 값을 넣음
                    stack_Operator.push(temp);
                } else if ((temp.equals(")"))) {// ) 일 경우 ( 전까지 스택을 계속 pop
                    while (!stack_Operator.check().equals("(")) {
                        formula_last += stack_Operator.pop() + " ";
                    }
                    stack_Operator.pop();// 현재 스택의 마지막 갑은 ( 이기네 pop하여 배열 count 감소 시킴
                }
 
                else if (stack_Operator.check().equals("("|| stack_Operator.check().equals("empty")) {
                    // 스택의 마지막값이 ( 경우 또는 현재 스택이 비어있을 경우 -
                    stack_Operator.push(temp);
                } else {// 현재 스택에 값이 존재하고 + 나 - 일 경우
                    formula_last += stack_Operator.pop() + " ";
                    stack_Operator.push(temp);
 
                }
            }
        }
        if (!stack_Operator.check().equals("empty")) {// 연산자 스택에 연산자가 존재할 경우
            formula_last += stack_Operator.pop() + " ";// 스택의 마지막값 출력
        }
        System.out.println(formula_last);
        StringTokenizer st03 = new StringTokenizer(formula_last);
        StringTokenizer st04 = new StringTokenizer(formula_last, "+-"false);
        Stack_num stack_num = new Stack_num(st03.countTokens() - (st03.countTokens() - st04.countTokens()));
        while (st03.hasMoreTokens()) {
            String temp = st03.nextToken();
            if (!(temp.equals("+"|| temp.equals("-"))) {
                stack_num.push(Integer.parseInt(temp));
            } else {// 연산자일경우
                int b = stack_num.pop();
                int a = stack_num.pop();
                if (temp.equals("+"))
                    stack_num.push(a + b);
                else
                    stack_num.push(a - b);
            }
        }
        int[] a = stack_num.getArr();
        System.out.println("total = " + a[0]);
    }
}
 
cs

제네릭 사용

package week_4;
 
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
 
public class StackAlgorithmsExample {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String formula = sc.nextLine().replaceAll(" """);
        ;// 중위 표기법 계산식
        String formula_last = "";// 후위 표기법
        StringTokenizer st01 = new StringTokenizer(formula, "+-()"true);
        Stack<String> stack_Operator = new Stack<>(); // 연산자 스택
        while (st01.hasMoreTokens()) {
            String temp = st01.nextToken();
            if (!(temp.equals("+"|| temp.equals("-"|| temp.equals("("|| temp.equals(")"))) {// 피연산자일경우
                formula_last += temp + " "//
            } else {// 연산자일경우
                if (temp.equals("(")) {// ( 일경우 연산자 스택에 값을 넣음
                    stack_Operator.push(temp);
                } else if ((temp.equals(")"))) {// ) 일 경우 ( 전까지 스택을 계속 pop
                    while (!stack_Operator.peek().equals("(")) {
                        formula_last += stack_Operator.pop() + " ";
                    }
                    stack_Operator.pop();// 현재 스택의 마지막 갑은 ( 이기네 pop하여 배열 count 감소 시킴
                }
 
                else if (stack_Operator.empty() || stack_Operator.peek().equals("(")) {
                    // 스택의 마지막값이 ( 경우 또는 현재 스택이 비어있을 경우 -
                    stack_Operator.push(temp);
                } else {// 현재 스택에 값이 존재하고 + 나 - 일 경우
                    formula_last += stack_Operator.pop() + " ";
                    stack_Operator.push(temp);
 
                }
            }
        }
        if (!stack_Operator.empty()) {// 연산자 스택에 연산자가 존재할 경우
            formula_last += stack_Operator.pop() + " ";// 스택의 마지막값 출력
        }
        System.out.println(formula_last);
        StringTokenizer st03 = new StringTokenizer(formula_last);
        Stack<Integer> stack_num = new Stack<>();
        while (st03.hasMoreTokens()) {
            String temp = st03.nextToken();
            if (!(temp.equals("+"|| temp.equals("-"))) {
                stack_num.push(Integer.parseInt(temp));
            } else {// 연산자일경우
                int b = stack_num.pop();
                int a = stack_num.pop();
                if (temp.equals("+"))
                    stack_num.push(a + b);
                else
                    stack_num.push(a - b);
            }
        }
        System.out.println("total = " + stack_num.pop());
    }
}
 
cs

 

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.