-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_day3.cpp
More file actions
101 lines (82 loc) · 1.69 KB
/
stack_day3.cpp
File metadata and controls
101 lines (82 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//Contains errors in prefix to postfix. Fix them whenever you get some time
#include<bits/stdc++.h>
#define MAX 1000
using namespace std;
char push(char a[], int top, char data){
if(top>=MAX){
cout<<"Stack Overflow\n";
return -1;
}
else{
a[++top] = data;
return top;
}
}
char pop(char a[], int *top){
if(*top<0){
cout<<"Stack underflow\n"<<endl;
return NULL;
}
else{
int temp = a[(*top)--];
return temp;
}
}
bool isEmpty(char a[], int top){
if(top<0)
return true;
}
char peek(char a[], int top){
return a[top];
}
int isOperand(char ch)
{
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
// A utility function to return precedence of a given operator
// Higher returned value means higher precedence
int Precedence(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
string infixToPostfix(char expression[], char a[], int top){
int i=0;
string result="";
for(int i=0; expression[i]; ++i){
if(isOperand[expression[i]])
result+=expression[i];
else if(expression[i]=='(')
push(a, &top, expression[i]);
else if(expression[i] == ')'){
while(!isEmpty(a, top) && peek(a, top) !='(')
result+=pop(a, &top);
pop(a, &top);
}
else{
while(!isEmpty(a, top) && Precedence(expression[i]) <= Precedence(peek(a, top)))
result += pop(a, &top);
push(a, &top, expression[i]);
}
}
while(!isEmpty(a,top))
result+=pop(a,top);
return result;
}
int main(){
//initialize stack
char a[MAX], top=-1;
char expression[] = "a+b*(c^d-e)^(f+g*h)-i"
string result = infixToPostfix(expression, a, top);
cout<<result<<endl;
}