Professional Documents
Culture Documents
STACKS
Divyam Agrawal
CSE
20103088
The conversion of Infix expression to postfix expression is easily performed by
using Stack linear data structure. The following algorithm is followed to perform
the conversion:-
• TIME COMPLEXITY
The algorithm runs across the stack once per element in the stack , but if it
encounters a closing bracket or an operator , it runs a backward loop until
a specified condition is fulfilled. So the time complexity is ,
• SPACE COMPLEXITY
The algorithm requires only a stack to store the input string of infix
expression and depends on the size of the input. It also requires an
additional variable irrespective of the size of input. So the space
complexity is,
#include<bits/stdc++.h>
using namespace std;
class Stack
{
public:
char Stack[1000];
int t = 0;
void push(char x)
{
t++;
Stack[t-1] = x;
}
void pop()
{
t--;
}
char top()
{
char a = Stack[t-1];
return a;
}
bool Empty()
{
bool d;
if(t==0)
{
d = true;
}
else
{
d = false;
}
return d;
}
};
int prec(char a)
{
int s;
if(a == '^')
{
s = 3;
}
else if(a == '/' || a == '*')
{
s = 2;
}
else if(a == '+' || a== '-')
{
s = 1;
}
else
{
s = -1;
}
return s;
}
void intopost(string s)
{
Stack s1;
string result;
for(int i =0; i<s.size() ; i++)
{
char c = s[i];
while(!s1.Empty())
{
result+=s1.top();
s1.pop();
}
cout<<" "<<result<<endl<<endl;
}
int main()
{
string s;
cout<<" Infix Expression : ";
s = "a+b*c^d/e-f";
cout<<s<<endl<<" Postfix Expression : ";
intopost(s);
cout<<" Infix Expression : ";
s = "a+b*(c^d-e)^(f+g*h)-i";
cout<<s<<endl<<" Postfix Expression : ";
intopost(s);
cout<<endl<<endl<<" Divyam Agrawal"<<endl<<" CSE"<<endl<<"
20103088";
return 0;
}
RESULTS