Need to create infix to postfix algorithm - c++

I need to implement infix to postfix conversion algorithm to compute the expression a+b*c-d/e
I also need to do this using queue (I believe 2 different queue stacks are needed)
I've created my queue class using a DoubleLinkList and now just need to create the algorithm for this problem. I'm pretty lost on how to go about it, though. Any help would be appreciated!
so far(And I know it's very wrong) I have:
string infix = "a+b*c-d/e";
Queue *holder = new Queue();
Queue *newstring = new Queue();
int length = infix.length();
char temp;
char prev;
for(int i=0; i<length; i++)
{
temp = infix[i];
if((temp == '+') || (temp == '-') || (temp == '*') || (temp == '/'))
{
if (holder->isEmpty())
{
holder->queue(temp);
}
if(temp<holder.enqueue())
{
}
}
holder->queue(temp);
}

I assume this is a homework assignment so it is important that you figure out the programming details on your own. The general outline of the algorithm is as follows:
Define a stack
Go through each character in the string
If it is between 0 to 9, append it to output string.
If it is left brace push to stack
If it is operator *+-/ then
If the stack is empty push it to the stack
If the stack is not empty then start a loop:
If the top of the stack has higher precedence
Then pop and append to output string
Else break
Push to the stack
If it is right brace then
While stack not empty and top not equal to left brace
Pop from stack and append to output string
Finally pop out the left brace.
If there is any input in the stack pop and append to the output string.

I think you should create a tree of operators and values.
You can convert from infix to postfix to prefix depending on your traversal order of the tree.
Your instructor may have give you assignments to convert between the three.
Here are some articles:
University of Texas
YouTube video
Wikipedia - Expression trees

Related

Runtime Error in Returning vector of vector from Level Order Traversal of binary tree

Given a binary tree, return the level order traversal of its nodes values, but we need to return a 2D integer array denoting the level order traversal of the given binary tree.
I tried to approach this as normal level order traversal but after each level put a NULL so that it will signify the new level in tree. If we encounter NULL in queue (using queue implementation) then it signifies that this level is completed so, we'll push NULL in queue. Below is my code -
vector<vector<int> > Solution::levelOrder(TreeNode* A) {
queue<TreeNode*>q;
q.push(A);
q.push(NULL);
vector<int>v;
vector<vector<int>>ans;
while(!q.empty()){
TreeNode* temp = q.front();
q.pop();
if(temp==NULL){
q.push(NULL);
ans.push_back(v);
v.clear();
}
else{
v.push_back(temp->val);
if(temp->left!=NULL)
q.push(temp->left);
if(temp->right !=NULL)
q.push(temp->right);
}
}
return ans;
}
I'm getting runtime error but unable to understand why ?
There might be other issues in this code, but I'd like to focus on this bit:
if (temp == NULL) {
q.push(NULL);
ans.push_back(v);
v.clear();
}
This means that if you pull a null pointer out of your queue, then you place a null pointer back into the queue and make ans bigger. But this means that your queue will never be empty, since every time you pull out the null sentinel you've added in you'll put it back, and ans will continue to grow until you run out of memory.
See if you can find another way of determining when a particular level in the tree ends.

Converting infix to postfix using c++

I'm trying to convert infix to postfix. I don't think my code is wrong but apparently it is because it doesn't work. I don't know what to change to make my code work properly.
(It worked for a bit before and now it doesn't)
I followed this code from geeksforgeeks: https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/ but I changed some of it because the code from the website was also wrong.
Sorry if my explanation is a bit unclear. Here's my code:
#include <bits/stdc++.h>
using namespace std;
int checks(char c)
{
if (c=='^')
{
return 1;
}
else if (c=='+' || c=='-')
{
return 2;
}
else if (c=='*' || c=='/')
{
return 3;
} else
{
return -1;
}
}
int main()
{
stack <char> stack;
string result, input;
cout<<"Enter your equation: ";
cin>> input;
for (int i=0; i<input.length(); i+=1)
{
if (input[i]=='(')
{
stack.push(input[i]);
} else if (isalnum(input[i]))
{
result+=input[i];
} else if (input[i]==')')
{
while(!stack.empty() && stack.top() != '(')
{
char c = stack.top();
stack.pop();
result += c;
}
if(stack.top() == '(')
{
char c = stack.top();
stack.pop();
}
} else
{
if (checks(stack.top()) >= checks(input[i]))
{
result+=stack.top();
stack.pop();
} else
{
stack.push(input[i]);
}
}
}
while(!stack.empty())
{
if (stack.top()=='(' || stack.top()==')')
{
stack.pop();
} else
{
result+=stack.top();
stack.pop();
}
}
cout<<"Result is: ";
cout<<result<<endl;
return 0;
}
Are your infix expressions using standard mathematical precedence? If so this will change things significantly compared to simple left to right evaluation.
You need to split your program into two phases. In the first phase you will parse the expression and build up the stack. In the second you will iterate over the stack and evaluate the result.
As I said, the parsing will be determined by the precedence. If you are using standard precedence then the usual approach (which you can read in Stroustrup's "The C++ Programming Language") is to use recursive descent. You would then have different precedences for parens, terms, factors, unary operators and literals. Use an enum for these, not magic numbers like 1, 2, 3.
You may skip step to actually create a tree structure , but have to keep in mind that infix notation is representable by tree while Polish notation is representable by stack. In (a+b)*(c+d) the * is topmost node, next level are two + and a, b,c,d. it's a symmetric tree because all operations commutative. But ((a+b)*(c+d))/3 is asymmetric, topmost node / is not commutative. Similar problem arise with -, because it's not commutative either.
E.g. possible option at each step can be (not a strict algorithm, but illustration how one should act, irt requires defense against malformed syntax)
Token is an "id".It's current level of tree node, scan further right
Token is a commutative operation. It's upper level of node. Next token would be a node of same level
Token is a non-commutative operation, / or -. It's upper level of node. Next token relates to node between current one and operation.
* and / have precedence above + and -, so they are nodes of lower level. E.g. a+b*c, First our tree was +: [a,b], then it is +:[a,*:[b,c]].
Token is (. Scan string and count all braces until you find matching ). E.g. each ( increases counter, each ) decreases. You found match if counter is 0. You have syntax error at hand if you get positive or negative while reaching terminal character..
Everything inside of () is a node of lower level. Scan it after finishing all upper levels.
To actually scan string, a state machine running in loop is required, the sign of finishing would be that there will be no tokens left to process. Can be recursive or not.
If you avoid creating tree, you have to go down and up along tokens in string itself, finding topmost node, push it to stack, then right and left nodes (in that order), push to stack, etc. When you pop stack, last-in first-out, operations would appear in proper order.
Paul Floyd is right to remind of that operator precedence can be used to sort order nodes or tokens, albeit doing it in std::stack is not possible because it got only push and pop operations and no reordering is possible, so you have to store that separately or scan and rescan string to push appropriate elements in.
(Note, than when you use some RPN calculator like on of those TI ones the stack of operations acts as a LILO stack, while when convert from syntax tree to RPN, it's LIFO)

Expression Tree from Infix Expression in C++ Structural Programming

struct node
{
char data;
node *left, *right;
};
constructTree(string expression)
{
for(i = 0; i < expression.length(); i++)
{
if(!(isOperator(expression[i]))
{
temp = createNode(expression[i]);
push(temp);
}
else
{
temp = createNode(expression[i]);
node *temp1, *temp2;
temp1 = pop();
temp2 = pop();
temp->left = temp1;
temp->right = temp2;
}
}
}
int main()
{
string expression = "(a+b)-c*(d/e)";
constructTree(expression);
}
I want to construct expression tree from infix expression which I will take as a string from the user. I tried so much now I am feeling tired of it. Some body please help me in making this expression tree from infix expression!
You are trying to write a parser.
There are so many ways to do this, with some ways being especially optimized for infix expressions, and others being more general.
I personally suggest reading about Recursive Descent parsers, as they are a good starting point to learn about parsers since they are relatively simple and intuitive.
A simple recursive descent parser that handles expression with addition, subtraction, multiplication, division and parentheses would look something like this (This is pseudocode!):
node* readExpr() {
return readAddOrSub();
}
node* readAddOrSub() {
leftTree = readMulOrDiv();
token = peekNextToken(); // look at the next token without consuming it
if (token == '+' || token == '-') {
readNextToken(); // skip operator
rightTree = readAddOrSub();
return an addition or subtraction node with leftTree and rightTree as its left and right sub-trees respectively;
} else {
return leftTree;
}
}
node* readMulOrDiv() {
leftTree = readAtom();
token = peekNextToken();
if (token == '*' || token == '/') {
readNextToken(); // skip operator
rightTree = readMulOrDiv();
return a multiplication node with leftTree and rightTree as its left and right sub-trees respectively;
} else {
return leftTree;
}
}
node* readAtom() {
token = readNextToken()
if (token == '(') {
result = readExpr();
read another token and make sure it's ')';
return result;
} else if (token is a number)
return node holding a number;
else if (token is a variable)
return node holding a variable;
else
error();
}
This assumes you have something that breaks up your string apart into tokens (e.g. "5*(a+12)" should be broken into 7 tokens: the number 5, '*', '(', the variable 'a', '+', the number 12, ')').
Operator precedence is captured by the way that functions that parse an opeator of a certain precedence level call the functions that handle the next level of precedence in a hierarchical fashion. More specifically, a function that tries to parse an addition/subtraction node (readAddOrSub) calls the function that parses the next level of precedence (readMulOrDiv) to get its left and right sub-trees.
Note that readAddOrSub (and readMulOrDiv) calls itself to read the right-subtee so that multiple additions can be chained together ("1+2+3"), but beware that this makes the parser inherently right-associative ("1+2+3" will be parsed as "1+(2+3)").
Of course, it's not very hard to make it left-associative, but I'll leave that to you as an exercise!
Some resources that might help:
Wikipedia article about recursive descent
A recursive descent parser that parses C# (written in C#)
A recursive descent expression parser written in C

Need help making a linked list program

So I have an assigment that consist of making a program that allows me to enter the integer 10 on a linked list after finding the value 10 on the list three times. The 10 that I have to insert needs to go after the third 10. The code that I made for this program is the following:
Linkedlist<int>*prt=new LinkedList<int>;
bool found = false;
int count;
while(ptr==NULL & !found)
{
if (ptr -> info == 10)
count ++;
if(count == 3)
found = true;
if(!found)
ptr = ptr -> next;
Node NewNode = new Node;
if(count == 3)
NewNode -> info = 10;
NewNode -> next = ptr -> next;
ptr -> next = NewNode;
}
I think the code I made is correct, however, I am kind of lost on how to turn this piece of code into a running program. Any help would be greatly appreciated.
You have multiple errors in your program. For one, the variable prt should probably be ptr. Also, your while condition should be using the && boolean operator instead of the & bitwise operator. From your description, it appears that the last two lines of your loop:
NewNode -> next = ptr -> next;
ptr -> next = NewNode;
Should only be invoked if count == 3. However, in it's current form they are being executed on every loop iteration. Likewise, you should only create a NewNode when you actually plan to do the insertion.
You're also checking the condition count == 3 multiple times including indirectly through the found variable. Each of these conditions could be collapsed into a single if like so:
if (count == 3) {
found = true;
Node NewNode = new Node;
NewNode->info = 10;
NewNode->next = ptr->next;
ptr->next = NewNode;
} else {
ptr = ptr->next;
}
You should strongly think about any loop that you write and what loop invariants you want to maintain through the loop as well as what thing is going to change on every loop iteration so that you can have a deterministic end to your loop.
Also, whenever you are dealing with a new type of data structure that you have never worked with before, I recommend drawing out a little diagram with boxes and arrows. This will help you figure out the process which you need to follow to get what you want.
I would start with an initial diagram and then a final diagram showing the picture you want. Then draw a marker that corresponds to the pointer that iterates across your list. Move the marker one time through the loop on each step. Then try to implement the steps you took with the marker in code form.
Here's some example starting diagrams that I drew using Google Docs:
Assume the dotted arrows represent NULL pointers. This gives you three potential starting cases for your linked list.

Using Stacks in C++ to Evaluate the Postfix Expression

Ok, I already have it in postfix notation and I am sending over a string variable that will have the postfix notation as something such as: 5 15 2 *+
Here is my code:
int evaluatePostFix(string postfix_expression){
//Create a new stack
stack<int> theStack;
//Loops while the postfix expression string still contains values
while(postfix_expression.length()>=1){
//Loops on a number an whitespace
while(isdigit(postfix_expression.at(0)) || isspace(postfix_expression.at(0))){
//Holds a number that is above two digits to be added to the stack
string completeNum;
if(isdigit(postfix_expression.at(0))){
//Add the digit so it can become a full number if needed
completeNum+=postfix_expression.at(1);
}
else {
//Holds the integer version of completeNum
int intNum;
//Make completeNum an int
intNum=atoi(completeNum.c_str());
//push the number onto the stack
theStack.push(intNum);
}
//Check to see if it can be shortened
if(postfix_expression.length()>=1){
//Shorten the postfix expression
postfix_expression=postfix_expression.substr(1);
}
}
//An Operator has been found
while(isOperator(postfix_expression.at(0))){
int num1, num2;
char op;
//Grabs from the top of the stack
num1=theStack.top();
//Pops the value from the top of the stack - kinda stupid how it can return the value too
theStack.pop();
//Grabs the value from the top of the stack
num2=theStack.top();
//Pops the value from the top of the stack
theStack.pop();
//Grab the operation
op=postfix_expression.at(0);
//Shorten the postfix_expression
postfix_expression=postfix_expression.substr(1);
//Push result onto the stack
theStack.push(Calculate(num1,num2, op));
}
}
return theStack.top();
}
The error I get is "Deque iterator not deferencable"
Any help that I can get on this error would be much appreciated.
btw I haven't used C++ in a couple of years so I'm a bit rusty.
It would be easier if you told us which line was causing the error by stepping through with a debugger. However, I think I may have spotted the error.
In this block of code
if(isdigit(postfix_expression.at(0))){
//Add the digit so it can become a full number if needed
completeNum+=postfix_expression.at(1);
}
You ask for the postfix_expression.at(1) without ever checking if that element exists. Since there is no check, you might be accessing bad memory locations.