Question

In: Computer Science

Introduced to data structure using java 2)One of the applications of stack is to convert infix...

Introduced to data structure using java

2)One of the applications of stack is to convert infix expressions to postfix. Given the following infix expression, use the stack method to convert it to postfix. Show your work.

x - y / (a + b) + z

3)write a generic method to find the maximum of three variables of generic type (i.e. type T).

Note that you must use the compareTo method to compare the values. Also, the code must return one of the values. Therefore the return type must be T.

Solutions

Expert Solution

import java.util.*;
public class DataStructuresEg
 {
    
    //Method to convert infix expression to postfix
      public static void infixToPostfix(String infix)
  {
    //Stack stk to store values
    Stack<Character> stk=new Stack<Character>();
    //String to store postfix expression
      String postfix="";
      //initializing variable i
      int i=0;
     //Loop to access each character in input expression 
    while(i<infix.length())
    {
        //if the input character is a letter or a digit
        if(Character.isLetter(infix.charAt(i))||Character.isDigit(infix.charAt(i)))
        {
          //add the input character to string postfix
            postfix+=" "+infix.charAt(i);
        }
        //else if the input character is an ')'
        else if(infix.charAt(i)=='(')
        {
          //push the input character into stack
            stk.push('(');

        }
        //else if the input character is ')'
        else if(infix.charAt(i)==')')
        {
            //Repeat  while stack is not empty and stack of top is "("
            while(stk.peek()!='(' && !stk.isEmpty())
            {
              //Delete the top element in stack and add to postfix
             postfix+=" "+stk.pop();
            }
            //if top element in stack is'('
            if(stk.peek()=='(')
            //Delete the top element in stack 
           stk.pop();
        }
        //else if the input character is blankspace do nothing
        else if(infix.charAt(i)==' ')
          {}
          //Else if the element is an operator
        else
        {
           //Repeat  while stack is not empty and 
           //precedence of stack of top is greaater thanor equalto precedence of input 
            while( !stk.isEmpty()&&(prec(infix.charAt(i))<=prec(stk.peek())))
             //Delete the top element in stack and add to postfix
                  postfix+=" "+stk.pop();
              //push the input character to stack
             stk.push(infix.charAt(i));
        
           
        }
       //increase i
        i++;
    }
    //Repeat  while stack is not empty 
    while(!stk.isEmpty())
    //Pop elements in stack and add to postfix
      postfix+=" "+stk.pop();
    System.out.println("Postfix Expression is");
    //Print the postfix expression
    System.out.println(postfix);
  } 
  //Function to find precedence of operator
  static int prec(char op)
  {
      int p=0;
      switch(op)
      {
        //if input is ^ precedence value is 3
         case '^':p=3;
          break;
          //if input is * or / or % precedence value is 2
          case '*':p=2;
          break;
          case '/':
          case '%': p=2;
                break;
                //if input is + or - precedence value is 1
        case '+':p=1;
        break;

        case '-':
                    p=1;
                    break;
      }
      return p;
  }
  //Generic function tofind maximum of three 
public static <T extends Comparable> void maxOfThree(T a,T b,T c)
{
  //Declaring generic variable max tostore mximum value
  T max;
  //if a is greater than b and c
  if(a.compareTo(b)>=0 && a.compareTo(b)>=0)
    max=a;
    //if b is greater than a and c
  else if(b.compareTo(c)>=0)
    max=b;
  else
    max=c;
  System.out.println("Maximum of three is: "+max);

}
  public static void main(String[] args) 
{
  //calling function to find maximum of three inputs of different types 
  maxOfThree(3,36, 8);
  maxOfThree(39.7,36.9, 0.8);
  maxOfThree('a','d','z');
 System.out.println("Enter infix expreession:");
 Scanner sc=new Scanner(System.in);

String input=sc.nextLine();
//calling function to find postfix expression
 infixToPostfix(input);

}
 }

Sample output


Related Solutions

Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Assignment #2 (JAVA) In assignment 1 you had used the data structure called Stack to evaluate...
Assignment #2 (JAVA) In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees. Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that a given expression could result in...
* the Algorithm: * write a java program to convert infix to postfix create(OpStk) OpStk.push("#") token...
* the Algorithm: * write a java program to convert infix to postfix create(OpStk) OpStk.push("#") token = nextToken() while (token != "#") if (token is an operand) append token to postfix expression else if (token is "(") // Left paren - Start of sub-expr OpStk.push( token ) else if (token is ")") // Right paren - End of sub-expr pop operators off the stack and append to the postfix expression - stop when you've popped a "(" else (token is...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a...
C++ Data Structure Write a program to change following infix expressions to postfix expressions using a stack a) D-B+C b) C*D+A*B c) (A*B)*C+D*F-C d) (A-4*(B-C)-D/E)*F
Using STL stack class, implement in C++ a function that converts an infix expression to postfix...
Using STL stack class, implement in C++ a function that converts an infix expression to postfix expression,
Java code for creating an Inventory Management System of any company - designing the data structure(stack,...
Java code for creating an Inventory Management System of any company - designing the data structure(stack, queue, list, sort list, array, array list or linked list) (be flexible for future company growth Java code for creating an initial list in a structure. Use Array (or ArrayList) or Linkedlist structure whichever you are confident to use. - Implement Stack, Queue, List type structure and proper operation for your application. Do not use any database. All data must use your data structures....
In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression...
In Java, write class InfixToPostfixConverter co convert an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers (to make things easier) such as (6 + 2) • 5 - 8 / 4 to a postfix expression. The postfix version (no parentheses are needed) of this infix expression is 6 2 + 5 * 8 4 / - The program should read the expression into StringBuilder or String infix and use the Stack and Stack Interface class...
Requirements Both the stack and queue were implemented correctly according data structure and java standard practices....
Requirements Both the stack and queue were implemented correctly according data structure and java standard practices. The stack was used to implement a post-fix calculator using push, pop, peek and other stack concepts. The queue was used to implement the palindrome using add, remove, insert and other queue concepts. Both implementations produced the expected output. All submission requirements were followed. Test Harness for the first part: public class StackCalcTest { public static void main(String[] args) { StackCalc stackCalc = new...
Please show solution and comments for this data structure using java.​ Implement a program in Java...
Please show solution and comments for this data structure using java.​ Implement a program in Java to convert an infix expression that includes (, ), +, -, *,     and / to postfix expression. For simplicity, your program will read from standard input (until the user enters the symbol “=”) an infix expression of single lower case and the operators +, -, /, *, and ( ), and output a postfix expression.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT