-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInfixToPostfix.cpp
More file actions
131 lines (105 loc) · 2.49 KB
/
InfixToPostfix.cpp
File metadata and controls
131 lines (105 loc) · 2.49 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include<bits/stdc++.h>
using namespace std;
struct Node{
char data;
struct Node *next;
}*top = NULL;
void push(char ch){
struct Node *t = new Node();
t->data = ch;
t->next = top;
top = t;
}
char pop(){
if(top==NULL){
cout << "Stack is empty\n";
return -1;
}else {
struct Node *t = top;
char x = t->data;
top = top->next;
delete t;
return x;
}
}
void Display(){
struct Node *t = top;
while(t){
cout << "t";
t = t->next;
}
cout << "\n";
}
int isBalanced(char *expr){
for(int i=0; expr[i]!='\0'; i++) {
if( expr[i] == '(' ){
push(expr[i]);
}else if ( expr[i] == ')' ) {
if(top == NULL){
return 0;
}
pop();
}
}
if(top == NULL){
return 1;
}else{
return 0;
}
}
int pre(char ch){
// if character is + or -, it is 1
if(ch == '+' || ch == '-'){
return 1;
}else if (ch == '*' || ch == '/'){
return 2;
}
return 0;
}
int isOperand(char ch){
// if operator then 0
if(ch == '+' || ch == '-' || ch == '*' || ch == '/'){
return 0;
}
return 1;
}
char * InfixToPostfix(char *infix){
// i to track infix and j to track postfix
int i = 0, j = 0;
char *postfix;
// find length of infix
int len = strlen(infix);
// declare postfix expr
postfix = new char[len];
// while infix is not read until last character
while(infix[i] != '\0'){
// check if operand, if so add to postfix
if(isOperand(infix[i])){
postfix[j++] = infix[i++];
}else{
// else check if infix[i] is greater than top of stack, if yes, then push to stack
if(pre(infix[i]) > pre(top->data)){
push(infix[i++]);
}else{
// else pop from stack and add to postfix
postfix[j++] = pop();
}
}
}
// if anything remains, pop and add to postfix
while(top != NULL){
postfix[j++] = pop();
}
// make last value of postfix as NULL character
postfix[j] = '\0';
// return the expression
return postfix;
}
int main()
{
char *infix = "a+b*c-d/e";
// in the InfixToPostfix method while checking predecence, empty stack may throw an error so initialse with #
push('#');
char *postfix = InfixToPostfix(infix);
printf("%s\n", postfix);
}