Posts

Showing posts with the label stack

Evaluate postfix expression

import java.util.Stack; class EvaluationPostfixExpression { static int evaluatePostfix(String postfix) { // stack to store operand Stack stack = new Stack (); int ex1, ex2, result; int i = 0; while(i Output Postfix : 234*+82/-, Result : 10

Infix to postfix conversion of regular expression | Set 2

Image
  import java.util.Stack; class InfixToPostfix { static String toPostfix(String infix) { // stack to store operators Stack stack = new Stack (); StringBuilder result = new StringBuilder(); // store final result int i = 0; while(i getPrecedence(/*ch=*/stack.peek(), /*isOperatorFromStack=*/true)) { // precendence of input operator is greater than operator // at stack top then add input operator to stack stack.push(ch); i++; } else { // precendence of input operator is Output Infix : ((a+b)*c)-d^e^f, Postfix : ab+c*def^^-

Infix to postfix conversion of regular expression | Set 1

import java.util.Stack; class InfixToPostfix { static String toPostfix(String infix) { // stack to store operators Stack stack = new Stack (); StringBuilder result = new StringBuilder(); // store final result int i = 0; while(i getPrecedence(stack.peek())) { // precendence of input operator is greater than operator // at stack top then add input operator to stack stack.push(ch); i++; } else { // precendence of input operator is Output Infix : a+b*c-d/e, Postfix : abc*+de/-

Parenthesis matching program

import java.util.Stack; import java.util.EmptyStackException; import java.util.Optional; class ParenthesisMatching { static boolean isBalanced(Optional equationOptional) { // if input is null or empty return false if(!equationOptional.isPresent()) { return false; } // convert string to char array char[] chars = equationOptional.get().toCharArray(); // create stack Stack stack = new Stack (); for(char ch : chars) { try { if(ch == '(') { stack.push('('); } else if(ch == ')') { stack.pop(); // return throws EmptyStackException if stack is empty } } catch(EmptyStackException e) { return false; } } return stack.empty() ? true : false; } public static void main(String[] args) { // positive case String str =...

Stack data structure

  Reference Problems