// Data structure project // // infix to prefix conversion // #include using namespace std; template class Stack { public: Stack (int m); ~Stack (); int StackIsFull(); int StackIsEmpty(); void Push(x e); void Pop(x& e); void PrintStack(); private: int maxsize; int top; x *p; }; void convert(char* f) { Stack s1(64); Stack s2(64); Stack s3(64); int i=0; char e; while(f[i] != '\0') { if (f[i] == '(' || f[i] == '{' || f[i] == '[') s1.Push(f[i]); else if (f[i] == ')' || f[i] == '}' || f[i] == ']'){ while(!s2.StackIsEmpty()){ s2.Pop(e); s1.Push(e); } while(!s1.StackIsEmpty()){ s1.Pop(e); if (e != '(' && e != '{' && e != '[') s2.Push(e); else break; } } else if (f[i] == '+' || f[i] == '-'){ while(!s1.StackIsEmpty()){ s1.Pop(e); if (e != '(' && e != '{' && e != '[') s3.Push(e); else{ s1.Push(e); break; } } s1.Push(f[i]); while(!s3.StackIsEmpty()){ s3.Pop(e); s1.Push(e); } while(!s2.StackIsEmpty()){ s2.Pop(e); s1.Push(e); } } else if (f[i] == '*' || f[i] == '/'){ s1.Push(f[i]); while(!s2.StackIsEmpty()){ s2.Pop(e); s1.Push(e); } } else s2.Push(f[i]); i++; } while(!s2.StackIsEmpty()){ s2.Pop(e); s1.Push(e); } s1.PrintStack(); } int main(){ char f[64]; char t; cout << "Data structure project\ninfix to prefix conversion\nseyed mohammad hoseini 871412306\n___________________________________\n\n"; do{ cout << "Enter a balanced infix expression :\n"; cin.getline(f,64); cout << "\nprefix :\n"; convert(f); cout << "\n\nTry again? (y/n) "; cin >> t; cin.ignore(); }while(t == 'y'); return 0; } template Stack::Stack(int m){ maxsize = m; top = -1; p = new x[maxsize]; } template Stack::~Stack(){ delete [] p; } template int Stack::StackIsFull(){ if (top == maxsize - 1) return 1; return 0; } template int Stack::StackIsEmpty(){ if (top == -1) return -1; return 0; } template void Stack::Push(x e){ if (!StackIsFull()){ top++; p[top] = e; } } template void Stack::Pop(x &e){ if (!StackIsEmpty()){ e = p[top]; top--; } } template void Stack::PrintStack(){ x e; if (!StackIsEmpty()){ Pop(e); PrintStack(); cout << e; Push(e); } }