Crazy

Постфикс нотација

Nov 4th, 2017
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.lang.reflect.Array;
  4. import java.util.NoSuchElementException;
  5. import java.util.ArrayList;
  6.  
  7.  
  8. interface Stack<E>{
  9.     public E pop();
  10.     public void clear();
  11.     public E peek();
  12.     public boolean isEmpty();
  13. }
  14.  
  15. class SLLNode<E>{
  16.     protected E data;
  17.     protected SLLNode succ;
  18.     SLLNode(){}
  19.     SLLNode(E data, SLLNode<E> succ){
  20.         this.data = data;
  21.         this.succ = succ;
  22.     }
  23. }
  24.  
  25. class StackList<E> implements Stack{
  26.     SLLNode<E> top;
  27.     StackList(){
  28.         top = null;
  29.     }
  30.     public void push(E data){
  31.         SLLNode<E> ins = new SLLNode<>(data, top);
  32.         top = ins;
  33.     }
  34.     public E pop(){
  35.         if(top == null) System.out.print("Nema elementi vo stekot. ");
  36.         E ret = top.data;
  37.         top = top.succ;
  38.         return ret;
  39.     }
  40.  
  41.     public void clear(){top = null;}
  42.  
  43.     public E peek(){return top.data;}
  44.  
  45.     public boolean isEmpty(){return (top==null);}
  46.  
  47. }
  48.  
  49. public class PostFixEvaluation {
  50.  
  51.     public static int postfix(String [] s) throws Exception{
  52.         StackList<Integer> stek = new StackList<>();
  53.         for(String x : s){
  54.             if(Character.isDigit(x.charAt(0)))
  55.                 stek.push(Integer.parseInt(x));
  56.  
  57.             else if(x.charAt(0) == '+')
  58.                 stek.push(stek.pop() + stek.pop());
  59.  
  60.             else if(x.charAt(0) == '-'){
  61.                 int vt = stek.pop();
  62.                 int pr = stek.pop();
  63.                 stek.push(pr - vt);
  64.             }
  65.  
  66.             else if(x.charAt(0) == '/'){
  67.                 int vt = stek.pop();
  68.                 int pr = stek.pop();
  69.                 stek.push(pr / vt);
  70.             }
  71.  
  72.             else if(x.charAt(0) == '*')
  73.                 stek.push(stek.pop() * stek.pop());
  74.         }
  75.         return stek.pop();
  76.     }
  77.  
  78.     public static void main(String[] args) throws Exception{
  79.  
  80.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  81.  
  82.         String expression = br.readLine();
  83.         char exp[] = expression.toCharArray();
  84.  
  85.         String [] ex = expression.split(" ");
  86.         System.out.print(postfix(ex));
  87.        
  88.         br.close();
  89.  
  90.     }
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment