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;
- import java.lang.Character;
- interface Stack<E>{
- public boolean isEmpty();
- public void clear();
- public void push(E x);
- public E pop();
- public E peek();
- }
- class Node<E>{
- E data;
- Node<E> next;
- Node(){
- data=null;
- next=null;
- }
- Node(E data,Node<E> next){
- this.data=data;
- this.next=next;
- }
- public E getData() {
- return data;
- }
- }
- class LinkedStack<E> implements Stack<E>{
- private Node<E> top;
- LinkedStack(){
- top=null;
- }
- public boolean isEmpty() {
- return top==null;
- }
- public E peek() {
- if(top!=null) return top.data;
- throw new NoSuchElementException();
- }
- public void clear() {
- top=null;
- }
- public E pop() {
- if(top!=null) {
- E popData=top.data;
- top=top.next;
- return popData;
- }
- throw new NoSuchElementException();
- }
- public void push(E x) {
- Node<E> newTop= new Node<E>(x,top);
- top=newTop;
- }
- }
- public class PostFixEvaluation{
- public static int postfiks(String[] exp) {
- LinkedStack<Integer> stack=new LinkedStack<>();
- for(int i=0;i<exp.length;i++) {
- if(Character.isDigit(exp[i].charAt(0))) {
- stack.push(Integer.parseInt(exp[i]));
- }
- if(exp[i].charAt(0)=='+') {
- int right=stack.pop();
- int left=stack.pop();
- int res=left+right;
- stack.push(res);
- }
- if(exp[i].charAt(0)=='-') {
- int right=stack.pop();
- int left=stack.pop();
- int res=left-right;
- stack.push(res);
- }
- if(exp[i].charAt(0)=='*') {
- int right=stack.pop();
- int left=stack.pop();
- int res=left*right;
- stack.push(res);
- }
- if(exp[i].charAt(0)=='/') {
- int right=stack.pop();
- int left=stack.pop();
- int res=left/right;
- stack.push(res);
- }
- }
- return stack.pop();
- }
- public static void main(String[] args) throws Exception{
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String expression = br.readLine();
- //char exp[] = expression.toCharArray();
- String[] argumenti=expression.split("\\s");
- System.out.println(postfiks(argumenti));
- br.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement