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

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.
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,
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
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...
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses....
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses. For example, the expression ( 11 + 12 ) * 13 would be written as 11 12 + 13 * Assume that ALWAYS there is a space between operands and operators in the input expression. Use two stacks, one to store the operands and one to store the operators. Your program only accpets following operators : ( ) + - / * Write a...
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.
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class...
Define empty methods in Stack class using LinkedList class in Java ------------------------------------------------------------------------------- //Stack class public class Stack{ public Stack(){ // use LinkedList class } public void push(int item){ // push item to stack } public int pop(){ // remove & return top item in Stack } public int peek(){ // return top item in Stack without removing it } public boolean isEmpty(){ // return true if the Stack is empty, otherwise false } public int getElementCount(){ // return current number...
0. Introduction. In this assignment you will implement a stack as a Java class, using a...
0. Introduction. In this assignment you will implement a stack as a Java class, using a linked list of nodes. Unlike the stack discussed in the lectures, however, your stack will be designed to efficiently handle repeated pushes of the same element. This shows that there are often many different ways to design the same data structure, and that a data structure should be designed for an anticipated pattern of use. 1. Theory. The most obvious way to represent a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT