Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list. This is only supposed to use THAT method, calling a normal Stack will give me a zero. I do have the conversion to postfix, but there may be error in there. But the main problem currently is the evaluation of postfix. I keep getting an error that I made for an empty stack, which I will include. For testing it is only supposed to take in single integers (nothing more.) This is supposed to read in input, (WITHOUT spaces, very basic.) Any and all corrections are welcome. Here is my code:
LinkedStack class:
public class LinkedStack {
private Node top;
private int size;
private class Node {
private Node next;
private Object data;
public Node(Object e, Node n)
{
this.data =
e;
this.next =
null;
}
}
public LinkedStack() {
this.top = null;
this.size = 0;
}
public int size() {
return this.size;
}
public Object top() {
if (isEmpty()) {
throw new
EmptyStackException("");
}
return this.top.data;
}
public void push(Object elem) {
Node nn = new
Node(elem,this.top);
this.top = nn;
this.size++;
}
public Object pop() throws EmptyStackException {
if (isEmpty()) {
throw new
EmptyStackException("");
}
Object temp = this.top.data;
this.top = this.top.next;
this.size--;
return temp;
}
public boolean isEmpty() {
return (this.top == null ||
this.size == 0 );
}
}
*My EmptyStackException*
public class EmptyStackException extends RuntimeException{
public EmptyStackException(String
err) {
super(err);
}
}
*And here is the infix to postfix, postfix eval, precedence check, and main:
import java.util.Scanner;
public class postfix {
//Read in infix expression check
//Covert infix to postfix check
//Evaluate postfix
//Display original infix, corresponding postfix, and
final result on screen
private static String convertToPostfix (String infix)
{
String postfixResult = new
String("");
LinkedStack stack = new
LinkedStack();
for (int i = 0; i <
infix.length(); ++i) {
char c =
infix.charAt(i);
if
(Character.isLetterOrDigit(c)) {
postfixResult += c;
}
else if (c ==
'(') {
stack.push(c);
}
else if (c ==
'(') {
while (!stack.isEmpty() &&
(char)stack.top() != '(') {
postfixResult +=
stack.pop();
}
if (!stack.isEmpty() &&
(char)stack.top() != '(') {
return null;
}
else {
stack.pop();
}
}
else {
while(!stack.isEmpty() && precedence(c)
<= precedence((char)stack.top()) ) {
postfixResult +=
stack.pop();
}
stack.push(c);
}
}
while(!stack.isEmpty()) {
postfixResult +=
stack.pop();
}
return
postfixResult;
}
public static int evalPostFix(String in) {
LinkedStack stack = new
LinkedStack();
for (int i = 0; i < in.length();
i++) {
char c =
in.charAt(i);
if
(Character.isDigit(c)) {
stack.push(c);
}
else {
int value1 =
(int)stack.pop();
int value2 =
(int)stack.pop();
switch(c) {
case '+':
stack.push(value2 + value1);
break;
case '-':
stack.push(value2 - value1);
break;
case '/':
stack.push(value2 / value1);
break;
case '*':
stack.push(value2 * value1);
break;
case '^':
stack.push(value2 ^ value1);
break;
}
}
}
int returnval =
(int)stack.pop();
return returnval;
}
static int precedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '/':
case '*':
return 2;
case '^':
return 3;
}
return -1;
}
public static void main(String [] args) {
//postfix obj = new
postfix();
Scanner sc= new
Scanner(System.in);
System.out.println("Infix : \t
");
String exp = sc.nextLine();
String postfix =
convertToPostfix(exp);
System.out.println("Postfix: " +
convertToPostfix(exp));
int evalPostFix =
evalPostFix(postfix);
System.out.println("Postfix
evaluation: " + evalPostFix);
}
}
There was an error in your LinkedStack.java file, inside Node class constructor, the next node was not getting initialized. Fixed it. There were so many casting errors in postfix.java, fixed it and now everything works fine (for single digit integers only, and no blank spaces in input).
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// LinkedStack.java
public class LinkedStack {
private Node top;
private int size;
private class Node {
private Node next;
private Object data;
public Node(Object e, Node n) {
this.data = e;
// assigning n as next node, earlier, it was assigned null
this.next = n;
}
}
public LinkedStack() {
this.top = null;
this.size = 0;
}
public int size() {
return this.size;
}
public Object top() {
if (isEmpty()) {
throw new EmptyStackException("");
}
return this.top.data;
}
public void push(Object elem) {
Node nn = new Node(elem, this.top);
this.top = nn;
this.size++;
}
public Object pop() throws EmptyStackException {
if (isEmpty()) {
throw new EmptyStackException("");
}
Object temp = this.top.data;
this.top = this.top.next;
this.size--;
return temp;
}
public boolean isEmpty() {
return (this.top == null || this.size == 0);
}
}
// postfix.java
import java.util.Scanner;
public class postfix {
// Read in infix expression check
// Covert infix to postfix check
// Evaluate postfix
// Display original infix, corresponding postfix, and final result on screen
private static String convertToPostfix(String infix) {
String postfixResult = new String("");
// initializing empty stack
LinkedStack stack = new LinkedStack();
for (int i = 0; i < infix.length(); ++i) {
char c = infix.charAt(i);
// If the scanned character is an operand, add it to output.
if (Character.isLetterOrDigit(c))
postfixResult += c;
// If the scanned character is an '(', push it to the stack.
else if (c == '(')
stack.push(c);
// If the scanned character is an ')', pop and output from the stack
// until an '(' is encountered.
else if (c == ')') {
while (!stack.isEmpty() && (Character) stack.top() != '(')
postfixResult += stack.pop();
if (!stack.isEmpty() && (Character) stack.top() != '(')
return null;
else {
stack.pop(); // removing ( from the stack
}
} else // an operator is found, removing from the stack and
// appending to postfixResult as long as precedence of
// current operator is less than or equal to preceedence of
// operator on stack's top
{
while (!stack.isEmpty()
&& precedence(c) <= precedence((Character) stack.top()))
postfixResult += stack.pop();
stack.push(c);
}
}
// removing all the operators from the stack, appending to result
while (!stack.isEmpty())
postfixResult += stack.pop();
return postfixResult;
}
public static int evalPostFix(String in) {
// creating a stack
LinkedStack stack = new LinkedStack();
// looping through each character
for (int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
// If the character is an operand, pushing to stack
if (Character.isDigit(c))
stack.push((int) c - '0'); // (pushing as as integer)
// If the character is an operator, pop top two values from stack,
// applying the operator
else {
int val1 = (Integer) stack.pop();
int val2 = (Integer) stack.pop();
switch (c) {
case '+':
stack.push(val2 + val1);
break;
case '-':
stack.push(val2 - val1);
break;
case '/':
stack.push(val2 / val1);
break;
case '*':
stack.push(val2 * val1);
break;
case '^':
stack.push((int) Math.pow(val2, val1));
break;
}
}
}
return (Integer) stack.pop();
}
static int precedence(char c) {
switch (c) {
case '+':
case '-':
return 1;
case '/':
case '*':
return 2;
case '^':
return 3;
}
return -1;
}
public static void main(String[] args) {
// postfix obj = new postfix();
Scanner sc = new Scanner(System.in);
System.out.println("Infix : \t ");
String exp = sc.nextLine();
String postfix = convertToPostfix(exp);
System.out.println("Postfix: " + convertToPostfix(exp));
int evalPostFix = evalPostFix(postfix);
System.out.println("Postfix evaluation: " + evalPostFix);
}
}
/*OUTPUT*/
Infix :
(3*5)-(8/4)+8
Postfix: 35*84/-8+
Postfix evaluation: 21
Convert infix to postfix, and evaluate postfix using custom Stack created using a singly linked list....
Im writing a method to evaluate a postfix expression. Using my own stack class. Here is my code but I keep getting a classcastexception where it says java.lang.Character cannot be cast to java.lang,Integer. Im not sure how to fix this. public class Evaluator { public static void evaluatePost(String postFix) { LinkedStack stack2 = new LinkedStack(); int val1; int val2; int result; for(int i = 0; i < postFix.length(); i++) { char m = postFix.charAt(i); if(Character.isDigit(m)) { stack2.push(m); } else { ...
JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...
I need assistance with this code. Is there any way I can create
this stack class (dealing with infix to postfix then postfix
evaluation) without utilizing <stdio.h> and
<math.h>?
____________________________________________________________________________________________
C++ Program:
#include <iostream>
#include <string>
#include <stdio.h>
#include <math.h>
using namespace std;
//Stack class
class STACK
{
private:
char *str;
int N;
public:
//Constructor
STACK(int maxN)
{
str = new char[maxN];
N = -1;
}
//Function that checks for empty
int empty()
{
return (N == -1);
}
//Push...
*JAVA* Can somebody take a look at my current challenge? I need to throw a different exception when a)(b is entered. It should throw "Correct number of parenthesis but incorrect syntax" The code is as follows. Stack class: public class ArrayStack<E> { private int top, size; private E arrS[]; private static final int MAX_STACK_SIZE = 10; public ArrayStack() { this.arrS = (E[]) new Object[MAX_STACK_SIZE]; this.top = size; this.size = 0;...
This code in C converts infix to postfix and evaluates it. The problem is that it only evaluates one digit expressions. I need to fix it so that it can evaluate 2 digits expressions as well. #include <stdio.h> #include <ctype.h> #include <string.h> #include <math.h> #define SIZE 100 char s[SIZE]; int top=-1; void infixToPostfix(char *infix, char *postfix); void postfixEvaluation(char *postfix); void push(char elem){ s[++top]=elem; } char pop(){ return(s[top--]); } int pr(char elem){ // Order of precedence switch (elem) { case '(':...
Help me to fix this code in C language. This code converts infix expressions to postfix and then evaluate the expression. Right now, it works with single digits. I need to modify it so that it can evaluate expressions with also 2 digits, example: (60+82)%72. Additionally I need to display an error when the parenthesis don't match like (89+8(. I have muted some line that would print the postfix expression with a space like: 22 8 + when the input...
Using ADT Stack: Evaluating infix expressions by converting them to postfix expressions Postfix notation: In a postfix expression, a binary operation follows its two opperands. The order of the operands in a infix expression is the same as in the corresponding postfix expression but the order of the operators might change based on the precedence of the operators and the existing of paranthses. Infix Postfix a + b a b + (a + b) * c a b + c...
Complete the following java program in which infix expressions should be converted to postfix expressions /** * An algebraic expression class that has operations such as conversion from infix * expression to postfix expression, * and evaluation of a postfix expression */ public class Expression { /** * The infix of this expression */ private String infix; /** * Constructs an expression using an infix. */ public Expression(String infix){ this.infix = infix; } /** * Converts an infix expression into...
Write a java code to implement the infix to postfix algorithm as
described below:
Algorithm convertTo Post fix ( infix) // Converts an infix expression to an equivalent postfix expression operatorStack = a new empty stack postfix = anew empty string while (infix has characters left to parse) nextCharacter =next nonblank character of infix switch (nextCharacter) { case variable: Append nextCharacter to postfix break case 'A' operatorStack.push (nextCharacter) break case '+ case '-' : case '*' : case '/' while...
i want similar for this code to solve two questions : 1- Write a program to convert a postfix expression to infix expression 2-Write a program to convert an infix expression to prefix expression each question in separate code ( so will be two codes ) #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack { char s[SIZE]; int top; }; void push(Stack *st, char c) { st->top++; st->s[st->top] = c;...