-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackInPre.cpp
More file actions
132 lines (129 loc) · 2.25 KB
/
stackInPre.cpp
File metadata and controls
132 lines (129 loc) · 2.25 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
132
//stack infix to prefix
#include<iostream>
#include <cctype>
#include<string>
using namespace std;
struct opr
{
char *data;
int top, size;
void init(int n)
{
size = n;
data = new char[size];
top = -1;
}
void push(char c)
{
if (top == size - 1) return;
data[++top] = c;
}
char pop()
{
if (top == -1) return 0;
return data[top--];
}
};
struct operand
{
std::string *data;
int top,size;
void init(int n)
{
size=n;
data=new std::string[size];
top=-1;
}
void push(std::string c)
{
if(top==size-1)
return;
data[++top]=c;
}
std::string pop()
{
if(top==-1)
return 0;
return data[top--];
}
};
int getlength(char s[])
{
int i=0;
while(s[i]!='\0')
i++;
return i;
}
int presi(char c)
{
switch(c)
{
case '^':return 3;
case '*':return 2;
case '/':return 2;
case '+':return 1;
case '-':return 1;
default:return 0;
}
}
bool shouldpop(char top, char current) {
// Agar stack ka operator zyada powerful hai ya barabar hai, toh pop kar
return presi(top) >= presi(current);
}
int main()
{
opr o1 ;
operand o2;
char a[100],i=0,j=0;
std::string arr[4];
fgets(a,100,stdin);
int len=getlength(a)-1;
o1.init(len);o2.init(len);
while(i<len)
{
if(a[i]=='(')
{
o1.push(a[i]);
}
else if(isalnum(a[i]))
{
o2.push(std::string(1,a[i]));
}
else if(presi(a[i])>0)
{
while(o1.top!=-1&&o1.data[o1.top]!='('&&shouldpop(o1.data[o1.top],a[i]))
{
arr[0]=o2.pop();
arr[1]=o2.pop();
arr[2]=o1.pop();
arr[3]=arr[2]+arr[1]+arr[0];
o2.push(arr[3]);
}
o1.push(a[i]);
}
else if(a[i]==')')
{
while(o1.data[o1.top]!='(')
{
arr[0]=o2.pop();
arr[1]=o2.pop();
arr[2]=o1.pop();
arr[3]=arr[2]+arr[1]+arr[0];
o2.push(arr[3]);
}
o1.pop();
}
i++;
}
while (o1.top != -1) {
arr[0] = o2.pop();
arr[1] = o2.pop();
arr[2] = o1.pop();
arr[3] = arr[2] + arr[1] + arr[0];
o2.push(arr[3]);
}
if (o2.top != -1)
{
std::cout << o2.pop() << std::endl;
}
}