Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package M03Java_Advanced.C01Java_Advanced.L01Stacks_and_Queues.Stacks_and_Queues_Exercises;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Scanner;
- import java.util.Stack;
- public class E09InfixToPostfix {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- List<Character> result = new LinkedList<>();
- Stack<Character> stack = new Stack<>();
- String[] input = sc.nextLine().split(" ");
- for (String s : input) {
- char ch = s.charAt(0);
- if (Character.isLetterOrDigit(ch)) {
- result.add(ch);
- } else if (ch == '(') {
- stack.push(ch);
- } else if (ch == ')') {
- while (!stack.isEmpty() && stack.peek() != '(') {
- result.add(stack.pop());
- }
- stack.pop();
- } else {
- while (!stack.isEmpty() && precedence(ch) <= precedence(stack.peek())) {
- result.add(stack.pop());
- }
- stack.push(ch);
- }
- }
- while (!stack.isEmpty()){
- result.add(stack.pop());
- }
- System.out.println(result.toString().replaceAll("[\\[\\],]", ""));
- }
- private static int precedence(char ch)
- {
- switch (ch)
- {
- case '+':
- case '-':
- return 1;
- case '*':
- case '/':
- return 2;
- case '^':
- return 3;
- }
- return -1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement