Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**Постфикс нотација
- Да се напише алгоритам кој ќе врши евалуација на израз во постфикс нотација.
- На влез се чита низа од знаци за изразот (стринг), а на излез се печати вредноста на изразот по евалуацијата.
- Име на класата (Java): PostFixEvaluation
- Input: Output:
- 1 2 + 3
- 7 4 - 3
- 0 3 / 0
- 5 2 * 10
- 100 20 - 80
- 1 2 3 * + 5 - 2
- 28 72 * 13 + 20 67 * + 3369
- 1 1 1 - - 1 + 1 + 3
- 60 80 * 20 40 * / 6
- 8 9 * 4 3 - + 2 3 6 * + - 53
- */
- // CODE
- import java.util.Scanner;
- 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();
- }
- }
- class LinkedStack<E> {
- private int count = 0;
- private SLLNode<E> top;
- public LinkedStack() {
- top = null;
- }
- public boolean isEmpty() {
- return (top == null);
- }
- public E peek() {
- if (top == null)
- throw new NoSuchElementException();
- return top.element;
- }
- public void clear() {
- top = null;
- }
- public void push(E x) {
- count++;
- top = new SLLNode<E>(x, top);
- }
- public E pop() {
- if (top == null)
- throw new NoSuchElementException();
- E topElem = top.element;
- top = top.succ;
- count--;
- return topElem;
- }
- public int getSize() {
- return count;
- }
- }
- public class PostFixEvaluation {
- private static int calculate(int number1, int number2, char c) {
- switch (c) {
- case '+':
- return (number2 + number1);
- case '-':
- return (number2 - number1);
- case '*':
- return (number2 * number1);
- case '/':
- return (number2 / number1);
- case '%':
- return (number2 % number1);
- default:
- return 0;
- }
- }
- public static boolean isOperator(char c) {
- return c == '+' || c == '-' || c == '*' || c == '/' || c == '%';
- }
- public static void PostFixEvaluation(String sequence) {
- LinkedStack<Integer> stack = new LinkedStack<Integer>();
- String[] splited = sequence.split(" ");
- for (int i = 0; i < splited.length; i++) {
- if (Character.isDigit(splited[i].charAt(0)))
- stack.push(Integer.parseInt(splited[i]));
- else if (isOperator(splited[i].charAt(0))) {
- stack.push(calculate(stack.pop(), stack.pop(), splited[i].charAt(0)));
- }
- }
- if (!stack.isEmpty())
- System.out.println(stack.pop());
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- String sequence = input.nextLine();
- PostFixEvaluation(sequence);
- input.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement