Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package kolokviumska;
- import java.util.NoSuchElementException;
- import java.util.Scanner;
- 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> {
- // Stekot e pretstaven na sledniot nacin:
- //depth e dlabochinata na stekot, a
- // elems[0...depth-1] se negovite elementi.
- 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 Postfix {
- public static int resultPostfix(char[] izraz)
- {
- ArrayStack<Integer> stekce=new ArrayStack<>(110);
- int number=0;
- for(int i=0;i<izraz.length;i++)
- {
- if(Character.isDigit(izraz[i]) && Character.isDigit(izraz[i]))
- {
- number=number*10 + Character.getNumericValue(izraz[i]);
- }
- if(Character.isDigit(izraz[i]) && !Character.isDigit(izraz[i]))
- {
- number=number*10 + Character.getNumericValue(izraz[i]);
- stekce.push(number);
- number=0;
- }
- if(izraz[i]=='+' || izraz[i]=='-' || izraz[i]=='*' || izraz[i]=='/')
- {
- int operandA=stekce.pop();
- int operandB=stekce.pop();
- if(izraz[i]=='+')
- {
- stekce.push(operandA+operandB);
- }
- else if(izraz[i]=='-')
- {
- stekce.push(operandB-operandA);
- }
- else if(izraz[i]=='*')
- {
- stekce.push(operandA*operandB);
- }
- else
- stekce.push(operandB/operandA);
- }
- }
- return stekce.pop();
- }
- public static void main(String[] args) {
- Scanner s=new Scanner(System.in);
- String s1=s.nextLine();
- char[]c=s1.toCharArray();
- int result=Postfix.resultPostfix(c);
- System.out.println(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement