Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

DATA STRUCTURE AND

ALGORITHM
Experiment no. 5
Name: Juee Jamsandekar ROLL NO:A090
Batch/semester: Btech IT/3rd Batch :2

Objective:

Part A: Infix expression to Postfix expression conversion


Part B: Postfix expression evaluation
Part C: Balanced Parenthesis checking

Part A: Infix expression to Postfix expression conversion


Code:
#include <iostream>
#include <stack>
using namespace std;

int priority (char alpha){


if(alpha == '+' || alpha =='-')
return 1;

if(alpha == '*' || alpha =='/')


return 2;
if(alpha == '^')
return 3;

return 0;
}
string convert(string infix)
{
int i = 0;
string postfix = "";

stack <int>s;

while(infix[i]!='\0')
{

if(infix[i]>='a' && infix[i]<='z'|| infix[i]>='A'&& infix[i]<='Z')


{
postfix += infix[i];
i++;
}
else if(infix[i]=='(')
{
s.push(infix[i]);
i++;
}

else if(infix[i]==')')
{
while(s.top()!='('){
postfix += s.top();
s.pop();
}
s.pop();
i++;
}
else
{
while (!s.empty() && priority(infix[i]) <= priority(s.top())){
postfix += s.top();
s.pop();
}
s.push(infix[i]);
i++;
}
}
while(!s.empty()){
postfix += s.top();
s.pop();
}

cout << "Postfix is : " << postfix;


return postfix;
}

int main()
{
string infix = "((a+(b*c))-d)+(e-f*(g/h))";
string postfix;
postfix = convert(infix);

return 0;
}
Output:

Part B: Postfix expression evaluation

Code:
#include<iostream>
#include<string.h>
#include<bits/stdc++.h>
using namespace std;
stack<int> s;

int main(){

//taking user input


string exp;
cout<<"Enter postfix expression: ";
cin>>exp;
for(int i=0;i<exp.length();i++){

if (isdigit(exp[i]))
s.push(exp[i] - '0');

else{
int op2=s.top();
s.pop();
int op1=s.top();
s.pop();

if(exp[i]=='+')
s.push(op1+op2);
else if(exp[i]=='-')
s.push(op1-op2);
else if(exp[i]=='*')
s.push(op1*op2);
else if(exp[i]=='/')
s.push(op1/op2);
}
}
cout<<"After evalution we get: "<<s.top();
return 0;
}

Output:

Part C: Balanced Parenthesis checking

Code:
#include <iostream> //main header file
#include <stack>
using namespace std;
void balance_parentheses();

int main()
{
int t;
cout << "Enter number of test cases:";
cin >> t;

for (int i = 0; i < t; i++) {


balance_parentheses();
}

return 0;
}

void balance_parentheses()
{
stack<char> a;
string s;
cout << "Enter string may or may not containing parentheses:";
cin >> s;

int flag = 0; //flag is an arbitrary variable


for (int i = 0; i < s.length(); i++)

{
if (s[i] == '{' || s[i] == '[' || s[i] == '(') {

a.push(s[i]);
flag = 1;
}
if (!a.empty()) {
if (s[i] == '}') {
if (a.top() == '{')
// top of the stack
{
a.pop();

continue;
}
else
break;
}
if (s[i] == ']') {
if (a.top() == '[') {
a.pop();
continue;
}
else
break;
}
if (s[i] == ')') {
if (a.top() == '(') {
a.pop();
continue;
}
else
break;
}
}
else {
break;
}
}

if ((a.empty()) && (flag == 1))


cout << "YES" << endl;
else
cout << "NO" << endl;
}

Output:

You might also like