A * B + (C - D / E)
AB*CDE/-+
A * B + (C - D / E) ((A * B) + (C - (D / E))) ((A B* (C (D E/-+ A B* C D E/-+
Initialise stack
Read symbol ch
While not end of expression
If ch is an operand
Append it to the postfix
If ch is (
Push ch
If ch is )
Pop stack
While popped value is not (
Append popped value to postfix
Pop stack
If ch is an operator
While stack not empty, and
top of stack != (, and
priority of top of stack >= priority of ch
Pop stack
Append popped value to postfix
Push ch
Read symbol ch
While stack not empty
Pop stack
Append popped value to postfix
Infix | Stack | Postfix |
---|---|---|
A * B + (C - D / E)
| Empty | |
* B + (C - D / E)
| Empty | A
|
B + (C - D / E)
| *
| A
|
+ (C - D / E)
| *
| AB
|
(C - D / E)
| +
| AB*
|
C - D / E)
| (+
| AB*
|
- D / E)
| (+
| AB*C
|
D / E)
| -(+
| AB*C
|
/ E)
| -(+
| AB*CD
|
E)
| /-(+
| AB*CD
|
)
| /-(+
| AB*CDE
|
+
| AB*CDE/-
| |
AB*CDE/-+
|
Read symbol ch While not end of expression If ch is an operand Push ch Else Pop RHS Pop LHS Compute LHS ch RHS Push result Read symbol ch Pop stack and print result
Postfix | Stack |
---|---|
AB*CDE/-+
| Empty |
B*CDE/-+
| A
|
*CDE/-+
| BA
|
CDE/-+
| 15
|
DE/-+
| C 15
|
E/-+
| DC 15
|
/-+
| EDC 15
|
-+
| 4 C 15
|
+
| 2 15
|
17
| |
boolean.h
).
#include "boolean.h" const int MAX_QUEUE = 100; typedef int queue_type[MAX_QUEUE]; //-------------------------------------------------------------- class queue { public: queue(void); void Initialize(void); boolean Enqueue(int Item); boolean Dequeue(int& Item); private: queue_type TheQueue; int Front,Rear; };