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 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
|
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
struct node{
char value;
struct node *link;
};
node *top;
class stack{
private:
int counter;
public:
node *pushInto(node*, char);
node *popOut(node*);
void traverseStack(node*);
int isStackEmpty();
stack()
{
top = nullptr;
counter = 0;
}
};
node *stack::pushInto(node *top, char a)
{
node *temp;
temp = new (struct node);
temp -> value = a;
temp -> link = top;
top = temp;
counter++;
return top;
}
node *stack::popOut(node *top)
{
node *temp;
char item;
if (top == nullptr)
{
cout << "Stack is empty";
}
else
{
temp = top;
item = temp -> value;
cout << item;
top = top -> link;
delete temp;
counter--;
}
return top;
}
void stack::traverseStack(node *top)
{
node *temp;
temp = top;
if (top == nullptr)
{
cout << "Stack is empty.";
}
else
{
while (temp != nullptr)
{
cout << temp -> value << endl;
temp = temp -> link;
}
}
}
int stack::isStackEmpty()
{
if (top == nullptr)
return 0;
return -1;
}
class infixToPostfix:public stack{
public:
bool isOperand(char);
bool isOperator(char);
int weightOfOperator(char);
char precedence(char, char);
void output(char[]);
};
bool infixToPostfix::isOperand(char a)
{
if (a >= 'A' && a <= 'Z')
return true;
return false;
}
bool infixToPostfix::isOperator(char a)
{
if (a == '*' || a == '/' || a == '+' || a == '-')
return true;
return false;
}
int infixToPostfix::weightOfOperator(char a)
{
int weight;
if (a == '*' || a == '/')
weight = 2;
else if (a == '+' || a == '-')
weight = 1;
else
weight = -1;
return weight;
}
char infixToPostfix::precedence(char a, char b)
{
if (weightOfOperator(a) > weightOfOperator(b))
{
return a;
}
return b;
}
void infixToPostfix::output(char a[])
{
const int length = 11;
// const int numberOperators = 5;
char output[length];
for (int i = 0; i < length; i++)
{
if (isOperand(a[i]))
{
output[i] = a[i];
}
else
{
top = pushInto(top, a[i]);
}
cout << output[i];
}
for (int i = 1; i < length; i+=2)
{
if (precedence(a[i], a[i + 1]))
{
top = popOut(top);
}
}
}
int main()
{
infixToPostfix result;
const int length = 11;
char infix1[length] = {'A', '*', 'B', '+', 'C', '*', 'D', '*', 'E', '+', 'F'}; //Initalize and declare first infix pattern
// char infix2[length] = {'A', '+', 'B', '*', 'C', '+', 'D', '+', 'E', '*', 'F'};
result.output(infix1);
cout << "\n";
// result.output(infix2);
return 0;
}
|