Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.NoSuchElementException;
- class SLLNode<E> {
- protected E element;
- protected SLLNode<E> succ;
- public SLLNode(E elem, SLLNode<E> succ) {
- this.element = elem;
- this.succ = succ;
- }
- @Override
- public String toString() {
- return element.toString();
- }
- }
- interface Stack<E> {
- public boolean isEmpty ();
- public E peek ();
- public void clear ();
- public void push (E x);
- public E pop ();
- }
- class ArrayStack<E> implements Stack<E> {
- private E[] elems;
- private int depth;
- @SuppressWarnings("unchecked")
- public ArrayStack (int maxDepth) {
- // Konstrukcija na nov, prazen stek.
- elems = (E[]) new Object[maxDepth];
- depth = 0;
- }
- public boolean isEmpty () {
- // Vrakja true ako i samo ako stekot e prazen.
- return (depth == 0);
- }
- public E peek () {
- // Go vrakja elementot na vrvot od stekot.
- if (depth == 0)
- throw new NoSuchElementException();
- return elems[depth-1];
- }
- public void clear () {
- // Go prazni stekot.
- for (int i = 0; i < depth; i++) elems[i] = null;
- depth = 0;
- }
- public void push (E x) {
- // Go dodava x na vrvot na stekot.
- elems[depth++] = x;
- }
- public E pop () {
- // Go otstranuva i vrakja elementot shto e na vrvot na stekot.
- if (depth == 0)
- throw new NoSuchElementException();
- E topmost = elems[--depth];
- elems[depth] = null;
- return topmost;
- }
- }
- public class PostFixEvaluation {
- public static boolean isNumber(String a) {
- for(int i=0; i<a.length(); i++) {
- if(Character.isDigit(a.charAt(i))) {
- continue;
- } else {
- return false;
- }
- }
- return true;
- }
- public static int calculate(char[]exp) {
- ArrayStack<Integer> stack = new ArrayStack<>(exp.length);
- String izraz=new String();
- for(int i=0; i<exp.length; i++) {
- izraz+=exp[i];
- }
- String []parts=izraz.split("\\s");
- int rezultat=0;
- for(int i=0; i<parts.length; i++) {
- if (isNumber(parts[i])) {
- stack.push(Integer.parseInt(parts[i]));
- } else {
- int pop1= stack.pop();
- int pop2=stack.pop();
- char operator = parts[i].charAt(0);
- if(operator == '+') {
- rezultat = pop2 + pop1;
- } else if(operator=='-') {
- rezultat=pop2-pop1;
- } else if(operator=='*') {
- rezultat=pop2*pop1;
- } else {
- rezultat=pop2/pop1;
- }
- if(i== parts.length-1) {
- if (stack.isEmpty()) {
- return rezultat;
- } else {
- return 0;
- }
- } else {
- stack.push(rezultat);
- }
- }
- }
- return -1;
- }
- public static void main(String[] args) throws Exception {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String expression = br.readLine();
- char exp[] = expression.toCharArray();
- System.out.print(calculate(exp));
- br.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement