You are on page 1of 8

Data Structure and Algorithm (DSA)

Lab # 06

Submitted to:
Sir Tanveer Ali

Submitted by:
Isra Imran
Warda-tu-Zahra
BSEE (17-21)
Section A
Submission Date:
24-05-2021

Pakistan Institute of Engineering and Applied


Sciences (PIEAS)
Implementation of Infix to Postfix
Converter and Expression Balance
Checker
Objectives:
The objectives of this lab are:

 Implement a stack to check if braces and brackets are balanced in an expression.

 Implement a stack to convert an infix expression to a postfix on

Background:
A stack data structure is one in which data is stored and retrieved in First in Last out order. This
structure is used in many problems such as balance check of brackets in an equation. Also conversion of
Infix expressions to postfix can also be done. An Infix expression is of the form
A+B*C

It can be converted to postfix expression which is

ABC*+

The infix to postfix conversion is useful and it can be performed by the use of stack data structure.

Lab 06(a)

1. Start from the beginning of an expression and push, into the stack, every open brace
you
encounter.
2. Pop if a closing brace is found.
3. Check the length of the stack when the expression is scanned completely.
4. Expression is balanced if stack length is zero and unbalanced otherwise .

Code:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
void BALANCE_CHECK(string expr)
{
stack<char> s;
int n = expr.length();
for (int i = 0; i <= n; i++)
{
if (expr[i] == '(' || expr[i] == '{' || expr[i] == '[')
{
s.push(expr[i]);
}
else if (expr[i] == ')' || expr[i] == '}' || expr[i] == ']')
{
if(s.empty()){
cout << expr[i] << " is unbalanced" << endl;
return;
}
else if((expr[i] == ')' && s.top() == '(') || (expr[i] == '}' && s.top() == '{') || (expr[i] == ']' && s.top()
== '[')){
s.pop();
}
}
}
if (s.empty())
{
cout << expr << " equation is balanced " << endl;
}
else
{
cout << expr << " equation is unbalanced" << endl;
}
}

int main()
{
string input1, input2, input3, input4;
input1 = " a + (b - c)";
input2 = "a + (b - c";
input3 = "}";
input4 = "{";
BALANCE_CHECK(input1);
BALANCE_CHECK(input4);
BALANCE_CHECK(input3);

return 0;
}
Output:

Lab 06(b):

1.Check every input and if the input is operand put it in the output stream otherwise push it
in the stack depending upon the precedence. For example, if the operator at top of the
stack
has more precedence than the input operator, pop the top of the stack to the output
stream and
push the input operator in the stack otherwise simply push the input operator.

2.If an open brace is found, push it into the stack. However, if a closed braces is found, pop
all elements up to open braces to the output stream. Once, all inputs are checked, pop the
elements of the stack to the output stream.

Code:
//# include<iostream>
// lab 06 b submitted by: ***Isra Imran
//***************************Warda tu Zahra

#include<bits/stdc++.h>
using namespace std;
int MAX=100;
class Stack {
int top;
char *a;
public:
// Maximum size of Stack

Stack() { top = -1;


a= new char[MAX];}
~Stack(){ // Destructor to free memory allocated to the stack
delete[] a;
}
bool push(char x);
char pop();
char Top();
bool isEmpty();
bool isFull();
void clear();
};
bool Stack::push(char x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow\n";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}
void Stack::clear(){
delete a;
top=-1;
}

char Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
char x = a[top--];
return x;
}
}
char Stack::Top()
{
if (top < 0) {
cout << "Stack is Empty\n";
return 0;
}
else {
char x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}

bool Stack::isFull()
{
return (top >= MAX-1);
}

//Function to return precedence of operators


int prec(char c)
{
if (c=='(')
return 5;
if(c == '^')
return 4;
else if(c == '*' || c == '/')
return 3;
else if(c == '+' || c == '-')
return 2;
else if(c==')')
return 1;
else
return -1;
}
bool preced(char c, char d)
{
int a,b;
a=prec(c);
b=prec(d);
return(a>=b);
}
// The main function to convert infix expression
//to postfix expression
void infixToPostfix(string s)
{
char temp;
Stack st;
int l = s.length();
string ns;
for(int i = 0; i < l; i++)
{

// If the scanned character is


// an operand, add it to output string.
if((s[i] >= 'a' && s[i] <= 'z') ||
(s[i] >= 'A' && s[i] <= 'Z'))
ns+=s[i];

else if(s[i]!=')')
{
if(!(st.isEmpty()))
{
if(s[i]!='('&&st.Top()!='('){
if(preced(st.Top(),s[i]))
{
temp=st.pop();
ns+=temp;
st.push(s[i]);

}
else {
st.push(s[i]);
}
}
if(s[i]=='('||st.Top()=='(')
{
st.push(s[i]);
}

}
else
st.push(s[i]);

if(s[i]==')')
{
while(!(st.isEmpty()) && st.Top() != '(')
{
char c=st.pop();
ns += c;
}
if(st.Top() == '(')
{
st.pop();
}
}
cout<<ns<<endl;
}
while(!(st.isEmpty()))
{
temp=st.pop();
ns += temp;
}
cout<<ns<<endl;
}

//Driver program to test above functions


int main()
{
string exp = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp);
return 0;
}

Output:

Discussion:
The above codes are to demonstrate the use of stack data structure. The first one is for balance check of
an equation. It first pushes the input expression in a stack and then checks for unbalanced brackets
while popping it and displays a string showing whether the expression is balanced or unbalanced.

The second part takes an infix expression and pushes it into stack. It then pops it out of stack converting
it to postfix.

You might also like