-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstackPrePo.cpp
More file actions
72 lines (72 loc) · 1.09 KB
/
stackPrePo.cpp
File metadata and controls
72 lines (72 loc) · 1.09 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
//stack prefix to postfix
#include<iostream>
#include<cctype>
#include<string>
#include <algorithm>
using namespace std;
struct inpo
{
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 "";
return data[top--];
}
};
int presi(char c)
{
switch(c)
{
case '^':return 3;
case '*':return 2;
case '/':return 2;
case '+':return 1;
case '-':return 1;
default:return 0;
}
}
int main()
{
inpo z;
std::string a;
std::cin >> a; // Reads until space or newline
std::reverse(a.begin(),a.end());
int len=a.length();
z.init(len);
std::string s[4];
int i=0;
while(i<len)
{
if(isalnum(a[i]))
{
z.push(std::string(1,a[i]));
}
else if(presi(a[i])>0)
{
s[0]=z.pop();
s[1]=z.pop();
s[2]=a[i];
s[3] = s[0] + s[1] + s[2] ;
z.push(s[3]);
}
i++;
}
if (z.top != -1)
{
cout << "Postfix expression: " << z.pop() << endl;
}
}