Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #define MAX 50
- char stack[MAX];
- int top=-1;
- int precedence(char item){
- if(item=='-' || item=='+')
- return 1;
- if(item=='*' || item=='/')
- return 2;
- if(item=='^')
- return 3;
- if(item=='(')
- return 0;
- return -1;
- }
- int isOperand(char ch){
- if(isdigit(ch) || islower(ch) || isupper(ch)){
- return 1;
- }
- else
- return 0;
- }
- void push(char input){
- if(top==MAX-1){
- printf("\nStack Overflow\n");
- }
- else{
- stack[++top]=input;
- }
- }
- int pop(){
- char item;
- if(top==-1){
- printf("\nStack Underflow\n");
- return -1;
- }
- else{
- item=stack[top--];
- }
- return item;
- }
- char str[2];
- char* getStr(char ch){
- str[0]=ch;
- str[1]='\0';
- return str;
- }
- void infixToPostfix(char exp[],char output[]){
- int n=strlen(exp);
- for(int i=0;i<n;i++){
- if(isOperand(exp[i])){
- strcat(output,getStr(exp[i]));
- }
- else if(exp[i]=='('){
- push(exp[i]);
- }
- else if(exp[i]==')'){
- while(stack[top]!='('){
- strcat(output,getStr(pop()));
- }
- pop();
- }
- else{
- while(top!=-1 && precedence(exp[i])<=precedence(stack[top])){
- strcat(output,getStr(pop()));
- }
- push(exp[i]);
- }
- }
- if(top!=-1){
- for(int i=top;exp[i]!=0;--i){
- strcat(output,getStr(stack[i]));
- }
- }
- }
- int main(){
- char exp[MAX],output[MAX];
- output[0]='\0';
- printf("Enter the expression:\n");
- scanf("%s",exp);
- infixToPostfix(exp,output);
- printf("\nPostfix expression is %s\n",output);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement