Calculate Postfix Expressions using Queues in Java

Problem:

You are given a list of postfix expressions. Calculate the result of the expressions using a stack. The first line of input n is the number of test cases followed by n expressions. Each expression begins with an integer t representing the number of characters in the expression, and then t characters follow which are either a number or an operand.

Output:

3
3 2 3 *
5 5 4 2 + -
9 5 6 2 + * 12 4 / -

6
1
37

Solution:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class ProblemC {

 public static void main(String[] args) {
  
  Queue<Integer> q = new LinkedList<Integer>();
  String output = "";
  Scanner scan = new Scanner(System.in);
  
  int testCases = scan.nextInt();
  
  for (int cases = 0; cases < testCases; cases++) {
   
   int t = scan.nextInt();
   
   for (int i = 0; i < t; i++)
    q.offer(scan.nextInt());
   
   output +=( "Test case "+(cases+1)+":" + "\n");
   
   while (!q.isEmpty()) {
    if (q.peek()%2 == 0)
     output += (q.poll() + "\n");
    else {
     output+= q.poll()+" ";
     output += q.poll() + "\n";
    }
   }
  }
  
  System.out.println(output);
 }
}


1 comment :

  1. liposuction fat Korea's #1 Liposculpture Clinic. Lydian plastic surgery is the home of VIP patients. Celebrities, Influencers and Diplomats all know and trust Doctor An and Lydian plastic surgery clinic to provide detailed results.

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact