You are on page 1of 2

/// Bài 5

#include <iostream>
#include <stack>

#include <string>

using namespace std;

struct Stack
{
int top;
char list[100];
};
void init(Stack &s)
{
s.top = 0;
}
bool Full(Stack s)
{
if (s.top == 1)
return 1;
return 0;
}
bool empty(Stack s)
{
if (s.top == -1)
return 1;
return 0;
}
void push(Stack& s, int x)

{
if (!Full(s))
s.list[++s.top] = x;
}
char top(Stack s)

{
return s.list[s.top];
}
void pop(Stack & s)
{
if (!empty(s))
--s.top;
}

int Rank(char s)
{
if (s == '+' || s == '-')return 1;
if (s == '*' || s == '/')return 2;
if (s == '^')return 3;
if (s == '(')return 0;
}
void instack(string s)
{
stack<char> st;
for (int i = 0; i < s.size(); i++)
{
if (s[i] >= '0' && s[i] <= '9')
{
cout << s[i] << " ";
}
else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/')
{
if (!st.empty())
{
if (Rank(s[i]) <= Rank(st.top()))
{
cout << st.top() << " ";
st.pop();
}
}
if (st.empty() || st.top() == '(' || Rank(s[i]) > Rank(st.top()))
{
st.push(s[i]);
}
}
else if (s[i] == '(')
{
st.push(s[i]);
}
else
{
while (st.top() != '(')
{
cout << st.top() << " ";
st.pop();
}
st.pop();
}
}
while (!st.empty())
{
cout << st.top() << " ";
st.pop();
}
}
void eraseStr(string x){
for (int i = 0; i < x.size(); i++)
{
if (x[i] == ' ')
{
x.erase(x.begin() + i);
i--;
}
}
}
int main()
{
string t;
getline(cin, t);
eraseStr(t);
instack(t);
return 0;
}

You might also like