Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include<iostream>
- using namespace std;
- #define MAX 1000
- struct stack {
- int top;
- char data[MAX];
- };
- void init(stack& s) {
- s.top = 0;
- }
- int isEmpty(stack s) {
- return (s.top == 0);
- }
- int isFull(stack s) {
- return (s.top == MAX);
- }
- void push(stack& s, char x) {
- if (!isFull(s)) {
- s.data[s.top] = x;
- s.top++;
- }
- }
- char top(stack s) {
- return s.data[s.top - 1];
- }
- char pop(stack& s) {
- if (!isEmpty(s)) {
- s.top--;
- return s.data[s.top];
- }
- }
- struct queue {
- int front, rear;
- char data[MAX];
- int n;
- };
- void initQueue(queue& q) {
- q.front = 0;
- q.rear = -1;
- q.n = 0;
- }
- bool isFullQueue(queue q) {
- return (q.n == MAX);
- }
- bool enQueue(queue& q, char x) {
- if (isFullQueue(q)) {
- return false;
- }
- q.rear = (q.rear + 1) % MAX;
- q.data[q.rear] = x;
- q.n++;
- return true;
- }
- bool isNumber(char c) {
- return c >= '0' && c <= '9';
- }
- bool isBest(char x, char y) {
- if (x == '(') {
- return false;
- }
- if (x == '*' || x == '/') {
- return true;
- }
- if (x == '+' || x == '-') {
- if (y == '*' || y == '/') {
- return false;
- }
- return true;
- }
- }
- int Precedence(char x)
- {
- if (x == '(')
- return 0;
- if (x == '+' || x == '-')
- return 1;
- if (x == '*' || x == '/' || x == '%')
- return 2;
- return 3;
- }
- void infixToPostfix(char p[], queue& q) {
- char x;
- stack s;
- init(s);
- for (int i = 0; i < strlen(p); i++) {
- if (p[i] == '(') {
- push(s, p[i]);
- }
- else if (isNumber(p[i])) {
- enQueue(q, p[i]);
- }
- else if (p[i] == ')') {
- do {
- x = pop(s);
- if (x != '(') {
- enQueue(q, x);
- }
- } while (x != '(');
- }
- else {
- x = top(s);
- while (isBest(x,p[i])) {
- x = pop(s);
- enQueue(q, x);
- x = top(s);
- }
- push(s, p[i]);
- }
- }
- while (!isEmpty(s)) {
- x = pop(s);
- enQueue(q, x);
- }
- }
- void Output(queue q) {
- for (int i = q.front; i <= q.rear; i++) {
- cout << q.data[i];
- }
- }
- void main() {
- queue q;
- initQueue(q);
- char p[] = "3+4";
- infixToPostfix(p, q);
- Output(q);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement