Stacks
Stacks
The problem is to transform the infix expression, that is an expression in which the operators lie
in between the operands, to the postfix expression or the reverse Polish notation in which the
operators are placed after the operands they are working on. Italizing makes the computation of
expressions on computers employing stack data structures quite easier.
Objectives:
Understand Infix and Postfix Notations: The first one represents computing formats where we
need to understand the difference between infix and postfix notations: The second one shows
us why computer science uses postfix notation.
Implement Stack Operations: Make appropriate utilization of the stack operations such as push
and pop during the conversion.
Apply Operator Precedence: To convert an infix expression to a postfix expression we can make
the use of operator precedence rules.
Write and Test the Algorithm: Write a C++ code for the above algorithm and run the code with
different infix expressions to check the correctness.
Algorithm:
#include<iostream>
string stack;
int top = -1;
void push(char c){
stack[++top]= c;
}
char pop(){
if(top==-1)
return -1;
else{
return stack[top--];
}
}
int main(){
string infix;
cout << "Enter an infix expression: ";
getline(cin, infix);
char y;
char z;
else{
cout << infix[i];
}
i++;
}
while(top!= -1){
z = pop();
cout << z;
}
return 0;
}
Objectives:
Understand Infix and Postfix Notations: The first one represents computing formats where we
need to understand the difference between infix and postfix notations. The second one shows
you why computer science uses postfix notation.
Implement Stack Operations: Make appropriate utilization of the stack operations such as push
and pop during the conversion.
Apply Operator Precedence: To convert an infix expression to a postfix expression we can make
the use of operator precedence rules.
Write and Test the Algorithm: Write a C++ code for the above algorithm and run the code with
different infix expressions to check the correctness.
Algorithm:
#include <bits/stdc++.h>
#include <iostream>
int main()
{
string s;
getline(cin, s);
// cout << s << endl;
cout << operation(s);
return 0;
}
stack<int> result;
string temp = "";
for (int i = 0; i <= str.size(); i++)
{
if (i < str.size() && str[i] != ' ' && !(str[i] == '+' || str[i] == '-'
|| str[i] == '*' || str[i] == '/'))
{
temp.push_back(str[i]);
}
else
{
if (!temp.empty())
{
int m = 0;
for (int i = 0; i < temp.size(); i++)
{
m = m * 10 + (temp[i] - '0');
}
result.push(m);
m = 0;
temp = "";
}
}
switch (str[i])
{
case '+':
result.push(a + b);
break;
case '-':
result.push(x - y);
break;
case '*':
result.push(a * b);
break;
case '/':
result.push(x / y);
break;
}
}
}