Sunteți pe pagina 1din 23

Infix to prefix dari source C

/*Infix to Prefix And Postfix*/


/*Assignment:5*/
/*Roll No:2102*/

#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 15
#define true 1
#define false 0

/*Structure Decvlaration*/
typedef struct
{
char data[MAX];
char top;
}STK;

/*Function Declarations*/
void input(char str[]);
void intopre(char str1[],char pre[]);
void intopost(char str1[],char post[]);
int isoperand(char sym);
int prcd(char sym);
void push(STK *s1,char elem);
int pop(STK *s1);
int empty(STK *s2);
int full(STK *s2);
void dis(char str[]);

void main()
{
STK s;
int cs,ans;
char str[MAX],pre[MAX],post[MAX];
clrscr();
do /*Using Do-while Loop*/
{
clrscr();
printf("
-----Program for Expressions-----");
printf("
Input The String:");
printf("
MENU:
");
printf("1.Infix to Prefix
");
printf("2.Infix to Postfix");
printf("
3.Exit");
cs=getche();

switch(cs) /*Using Switch Case*/


{
case 1:
intopre(str,pre);
break;
case 2:
intopost(str,post);
break;
case 3:
break;
default:
printf("
Enter a Valid Choise!"); /*Default Case*/
break;
}
printf("
Do you wish to Continue?(y/n)");
ans=getche();
}while(ans=='y'||ans=='Y'); /*Condition for Do-while loop*/

getch();
}

/**************************************************/
/*To Input String*/
/**************************************************/
void input(char str)
{
printf("Enter the Infix String:");
scanf("%s",str);
}

/**************************************************/
/*To Covert Infix To Prefix*/
/**************************************************/
void intopre(STK s1,char str1[],char pre[])
{
int len,flag;
len=strlen(str1);
int check=0,cnt=len-1,pos=0;
char elem;
while(cnt>=0) /*while condition*/
{
flag=0;
if(isoperand(str1[cnt])) /*Checking for Operand*/
{
printf("%c",str1[cnt]);
cnt--;
pos++;
}
else
{
check=prcd(str1[cnt]);
while(check==false)
{
pre[pos]=str1[cnt];
flag=1;
pos++;
cnt--;
}
if(flag==0)
{
elem=pop(&s1);
printf("%c",elem);
}
}

}
}

/**************************************************/
/*To Convert Infix To Postfix*/
/**************************************************/
void intopost(STK s1,char str1[],char post[])
{
int len;
len=strlen(str1);
int check=0,cnt=len-1,pos=0;

/**************************************************/
/*To Check For Operand*/
/**************************************************/
int isoperand(char sym)
{
if('A'<sym<'Z'||'a'<sym<'z')
return(true);
return(false);
}

/**************************************************/
/*To Check The Precedence*/
/**************************************************/
int prcd(char sym)
{

/**************************************************/
/*To Display String*/
/**************************************************/
void dis(char str[])
{

/******************************************/
/*Push Function Definition*/
/******************************************/
void push(STK *s1,char elem)
{
if(!full(s1))
{
s1->top++; /*Incrementing top*/
s1->data[s1->top]=elem; /*Storing element*/
}
else
printf("
Stack is Full!");
}

/******************************************/
/*Full Function Definition*/
/******************************************/
int full(STK *s2)
{
if(s2->top==MAX) /*Condition for Full*/
return(true);
return(false);
}

/******************************************/
/*Pop Function Definition*/
/******************************************/
int pop(STK *s1)
{
char elem;
if(!empty(s1))
{
elem=s1->data[s1->top]; /*Storing top stack element in elem*/
s1->top--; /*Decrementing top*/
return(elem);
}
return(false);
}

/******************************************/
/*Empty Function Definition*/
/******************************************/
int empty(STK *s2)
{
if(s2->top==-1) /*Condition For Empty*/
return(true);
return(false);
}

C++
Infix to prefix

Algorithm infix2postfix(infix expression string, postfix expression string)


{
   char *i,*p;

   i = first element in infix expression


   p = first element in postfix expression

   while i is not null


   {
      while i is a space or tab
      {
         increment i to next character in infix expression;
      }

      if( i is an operand )
      {
         p = i;
         increment i to next character in infix expression;
         increment p to next character in postfix expression;
      }

      if( i is '(' )
      {
         stack_push(i);
         increment i to next character in infix expression;
      }

      if( i is ')' )
      {
         while( element at top of stack != '(' )
         {
            p = element at top of stack;
            increment p to next character in postfix expression;
         }
         increment i to next character in infix expression;
      }

      if( i is an operator )
      {
         if( stack is empty )
             stack_push(i);
         else
         {

            while priority(element at top of stack) >= priority(i)


            {
               p = element at top of stack;
               increment p to next character in postfix expression;
            }
            stack_push(i);
         }
         increment i to next character in infix expression;
      }
   }
   while stack is not empty
   {
      p = stack_pop()
      increment p to next character in postfix expression;
   }
   p = '\0';
}

C++
Infix to postfix

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 10
#define EMPTY -1

struct stack
{
    char data[MAX];
    int top;
};

int isempty(struct stack *s)


{
    return (s->top == EMPTY) ? 1 : 0;
}

void emptystack(struct stack* s)


{
    s->top=EMPTY;
}

void push(struct stack* s,int item)


{
    if(s->top == (MAX-1))
    {
        printf("\nSTACK FULL");
    }
    else
    {
        ++s->top;
        s->data[s->top]=item;
    }
}

char pop(struct stack* s)


{
    char ret=(char)EMPTY;
    if(!isempty(s))
    {
        ret= s->data[s->top];
        --s->top;
    }
    return ret;
}

void display(struct stack s)


{
    while(s.top != EMPTY)
    {
        printf("\n%d",s.data[s.top]);
        s.top--;
    }
}

int isoperator(char e)
{
    if(e == '+' || e == '-' || e == '*' || e == '/' || e == '%')
        return 1;
    else
        return 0;
}

int priority(char e)
{
    int pri = 0;

    if(e == '*' || e == '/' || e =='%')


        pri = 2;
    else
    {
        if(e == '+' || e == '-')
            pri = 1;
    }
    return pri;
}

void infix2postfix(char* infix, char * postfix, int insertspace)


{
    char *i,*p;
    struct stack X;
    char n1;
    emptystack(&X);
    i = &infix[0];
    p = &postfix[0];

    while(*i)
    {
        while(*i == ' ' || *i == '\t')
        {
            i++;
        }

        if( isdigit(*i) || isalpha(*i) )


        {
            while( isdigit(*i) || isalpha(*i))
            {
                *p = *i;
                p++;
                i++;
            }
            /*SPACE CODE*/
            if(insertspace)
            {
                *p = ' ';
                p++;
            }
            /*END SPACE CODE*/
        }

        if( *i == '(' )
        {
            push(&X,*i);
            i++;
        }

        if( *i == ')')
        {
            n1 = pop(&X);
            while( n1 != '(' )
            {
                *p = n1;
                p++;
                /*SPACE CODE*/
                if(insertspace)
                {
                    *p = ' ';
                    p++;
                }
                /*END SPACE CODE*/
                n1 = pop(&X);
            }
            i++;
        }

        if( isoperator(*i) )
        {
            if(isempty(&X))
                push(&X,*i);
            else
            {
                n1 = pop(&X);
                while(priority(n1) >= priority(*i))
                {
                    *p = n1;
                    p++;
                    /*SPACE CODE*/
                    if(insertspace)
                    {
                        *p = ' ';
                        p++;
                    }
                    /*END SPACE CODE*/
                    n1 = pop(&X);
                }
                push(&X,n1);
                push(&X,*i);
            }
            i++;
        }
    }
    while(!isempty(&X))
    {
        n1 = pop(&X);
        *p = n1;
        p++;
        /*SPACE CODE*/
        if(insertspace)
        {
            *p = ' ';
            p++;
        }
        /*END SPACE CODE*/
    }
    *p = '\0';
}

int main()
{
    char in[50],post[50];

    strcpy(&post[0],"");
    printf("Enter Infix Expression : ");
    fflush(stdin);
    gets(in);
    infix2postfix(&in[0],&post[0],1);
    printf("Postfix Expression is : %s\n",&post[0]);

    return 0;
}
/* SAMPLE OUTPUT:
Enter Infix Expression : A + B + C / (E - F)
Postfix Expression is : A B + C E F - / +  
*/

convert(-^-) with tree


Algorithm postfix2exptree(postfix string, root<i.e. ptr to root node of exp tree>)
{
   NODES newnode,op1,op2;

   p = first element in postfix expression;


   while(p is not null)
   {
      while(p is a space or a tab)
      {
         increment p to next character in postfix expression;
      }
      
      if( p is an operand )
      {
         newnode = ADDRESS OF A NEW NODE;
         newnode->element = p;
         newnode->left = NULL;
         newnode->right = NULL;
         stack_push(newnode);
      }
      else
      {
         op1 = stack_pop();
         op2 = stack_pop();
         newnode = ADDRESS OF A NEW NODE;
         newnode->element = p;
         newnode->left = op2;
         newnode->right = op1;
         stack_push(newnode);
      }
      increment p to next character in postfix expression;
   }
   root = stack_pop();
}

Finish with C

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX 10
#define EMPTY -1

struct node
{
    char element;
    struct node *left,*right;
};

struct stack
{
    struct node *data[MAX];
    int top;
};

int isempty(struct stack *s)


{
    return (s->top == EMPTY) ? 1 : 0;
}

void emptystack(struct stack* s)


{
    s->top=EMPTY;
}

void push(struct stack* s, struct node *item)


{
    if(s->top == (MAX-1))
    {
        printf("\nSTACK FULL");
    }
    else
    {
        ++s->top;
        s->data[s->top]=item;

    }
}

struct node* pop(struct stack* s)


{
    struct node *ret=NULL;
    if(!isempty(s))
    {
        ret= s->data[s->top];
        --s->top;
    }
    return ret;
}

void postfix2exptree(char* postfix, struct node **root)


{
    struct stack X;
    struct node *newnode,*op1,*op2;
    char *p;
    p = &postfix[0];
    emptystack(&X);
    while(*p)
    {

        while(*p == ' ' || *p == '\t')


        {
            p++;
        }

        if(isalpha(*p) || isdigit(*p))
        {
            newnode = (struct node*)malloc(sizeof(struct node));
            newnode->element = *p;
            newnode->left = NULL;
            newnode->right = NULL;
            push(&X,newnode);
        }
        else
        {
            op1 = pop(&X);
            op2 = pop(&X);
            newnode = (struct node*)malloc(sizeof(struct node));
            newnode->element = *p;
            newnode->left = op2;
            newnode->right = op1;
            push(&X,newnode);
        }
        p++;
    }
    *root = pop(&X);
}

void inorder(struct node *x)


{
    if(x != NULL)
    {
        inorder(x->left);
        printf("%c ",x->element);
        inorder(x->right);
    }
}

void preorder(struct node *x)


{
    if(x != NULL)
    {
        printf("%c ",x->element);
        preorder(x->left);
        preorder(x->right);
    }
}

void postorder(struct node *x)


{
    if(x != NULL)
    {
        postorder(x->left);
        postorder(x->right);
        printf("%c ",x->element);
    }
}

int main()
{
    struct node *r;
    postfix2exptree("A B C * +",&r);
    printf("Inorder = ");
    inorder(r);
    printf("\nPreorder = ");
    preorder(r);
    printf("\nPostorder = ");
    postorder(r);
    return 0;
}
/* OUTPUT:
Inorder = A + B * C
Preorder = + A * B C
Postorder = A B C * +
*/

Source Equal
#include <stdio.h>
#include <ctype.h>

#define MAX 50
#define EMPTY -1

struct stack
{
    int data[MAX];
    int top;
};
void emptystack(struct stack* s)
{
    s->top = EMPTY;
}

void push(struct stack* s,int item)


{
    if(s->top == (MAX-1))
    {
        printf("\nSTACK FULL");
    }
    else
    {
        ++s->top;
        s->data[s->top]=item;
    }
}

int pop(struct stack* s)


{
    int ret=EMPTY;
    if(s->top == EMPTY)
        printf("\nSTACK EMPTY");
    else
    {
        ret= s->data[s->top];
        --s->top;
    }
    return ret;
}

void display(struct stack s)


{
    while(s.top != EMPTY)
    {
        printf("\n%d",s.data[s.top]);
        s.top--;
    }
}

int evaluate(char *postfix)


{
    char *p;
    struct stack stk;
    int op1,op2,result;

    emptystack(&stk);
    p = &postfix[0];
    while(*p != '\0')
    {
       /* removes tabs and spaces */
        while(*p == ' ' || *p == '\t')
        {
            p++;
        }
      /* if is digit */
        if(isdigit(*p))
        {
            push(&stk,*p - 48);
        }
        else
        {
           /* it is an operator */
            op1 = pop(&stk);
            op2 = pop(&stk);

            switch(*p)
            {
                case '+':
                    result = op2 + op1;
                    break;

                case '-':
                    result = op2 - op1;
                    break;

                case '/':
                    result = op2 / op1;
                    break;

                case '*':
                    result = op2 * op1;
                    break;

                case '%':
                    result = op2 % op1;
                    break;

                default:
                    printf("\nInvalid Operator");
                    return 0;
            }
            push(&stk,result);
        }
        p++;
    }
    result = pop(&stk);
    return result;
}

int main()
{
    char exp[MAX];
    printf("Enter Postfix Expression : ");
    gets(exp);
    printf("%s EQUALS %d\n",exp,evaluate(&exp[0]));
    return 0;
}
/* SAMPLE OUTPUT:
Enter Postfix Expression : 3 5 + 2 /
3 5 + 2 / EQUALS 4
*/

Coba yang ini pakai C


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX 10
#define EMPTY -1

struct node
{
    char kind;
    char op;
    int number;
    struct node *left,*right;
};

struct stack
{
    struct node *data[MAX];
    int top;
};

int isempty(struct stack *s)


{
    return (s->top == EMPTY) ? 1 : 0;
}

void emptystack(struct stack* s)


{
    s->top=EMPTY;
}

void push(struct stack* s, struct node *item)


{
    if(s->top == (MAX-1))
    {
        printf("\nSTACK FULL");
    }
    else
    {
        ++s->top;
        s->data[s->top]=item;

    }
}

struct node* pop(struct stack* s)


{
    struct node *ret=NULL;
    if(!isempty(s))
    {
        ret= s->data[s->top];
        --s->top;
    }
    return ret;
}

void postfix2exptree(char* postfix, struct node **root)


{
    struct stack X;
    struct node *newnode,*op1,*op2;
    char numberextract[5];
    char *p;

    emptystack(&X);
    p = &postfix[0];
    strcpy(numberextract,"");
    while(*p)
    {

        while(*p == ' ' || *p == '\t')


        {
            p++;
        }

        if(isdigit(*p))
        {
            while(isdigit(*p))
            {
                strcat(numberextract,p);
                p++;
            }

            newnode = (struct node*)malloc(sizeof(struct node));


            newnode->kind = 'N';
            newnode->number = atoi(numberextract);
            newnode->left = NULL;
            newnode->right = NULL;
            push(&X,newnode);
            strcpy(numberextract,"");
        }
        else
        {
            op1 = pop(&X);
            op2 = pop(&X);
            newnode = (struct node*)malloc(sizeof(struct node));
            newnode->kind = 'O';
            newnode->op = *p;
            newnode->left = op2;
            newnode->right = op1;
            push(&X,newnode);
        }
        p++;
    }
    *root = pop(&X);
}

int evaluatetree(struct node *x)


{
   if( x->kind == 'O' )
    {
      int op1 = evaluatetree( x->left );
      int op2 = evaluatetree( x->right );
      switch ( x->op )
        {
         case '+':  return op1 + op2;
         case '-':  return op1 - op2;
         case '*':  return op1 * op2;
         case '/':  return op1 / op2;
         default:   return 0;
      }
   }
    else
       return (x->number);
}

void inorder(struct node *x)


{
    if(x != NULL)
    {
        inorder(x->left);

        if(x->kind == 'O')
            printf("%c ",x->op);
        else
            printf("%d ",x->number);

        inorder(x->right);
    }
}

void preorder(struct node *x)


{
    if(x != NULL)
    {
        if(x->kind == 'O')
            printf("%c ",x->op);
        else
            printf("%d ",x->number);

        preorder(x->left);
        preorder(x->right);
    }
}

void postorder(struct node *x)


{
    if(x != NULL)
    {
        postorder(x->left);
        postorder(x->right);

        if(x->kind == 'O')
            printf("%c ",x->op);
        else
            printf("%d ",x->number);
    }
}

int main()
{
    struct node *r;
    postfix2exptree("100 50 - 2 /",&r);
    printf("Inorder = ");
    inorder(r);
    printf("\nPreorder = ");
    preorder(r);
    printf("\nPostprder = ");
    postorder(r);
    printf("\nResult = %d\n",evaluatetree(r));
    return 0;
}
/* OUTPUT:
Inorder = 100 - 50 / 2
Preorder = / - 100 50 2
Postprder = 100 50 - 2 /
Result = 25
*/

Yang Lain

#include <iostream>
#include <string>
#include <stack>

using namespace std;

//i love macros


#define isOp(x) (x=='-'||x=='+'||x=='/'||x=='*')
#define isHigh(x) (x=='*'||x=='/')
#define isLow(x) (x=='-'||x=='+')
#define isSame(x, y) ((isHigh(x) && isHigh(y)) ||(isLow(x) && isLow(y)))
#define isClose(x) ((x==']')||(x==')')||(x=='}'))
#define isOpen(x) ((x=='[')||(x=='(')||(x=='{'))

string reverse(string s)
{
string tar;

for(int i = s.size(); i >= 0; i--)


{
tar += s[i];
}
return tar;
}

string infix2prefix(string source)


{
stack<char> output;
stack<char> ops;
string eq(reverse(source)); //reverse equation
char c;
//for each element in equation
for(int i = 0; i < eq.size(); i++)
{
c = eq[i]; //prevent repeated dereferencing

//if not /-+*[]{}()


if((!isOp(c))&&(!isClose(c))&&(!isOpen(c)))
output.push(c);

//if is )}]
if(isClose(c))
ops.push(c);
//if is /+-*^
if(isOp(c))
{
//if stack is empty put operator on stack
if(ops.empty())
{
ops.push(c);
}else{
//else if top of stack is )]or} push operator on stack
if(isClose(ops.top()))
{
ops.push(c);
}
//is precedence is the same or higher push it onto
//operator stack...else, push it straight to output
//stack
if(isSame(c, ops.top())||isHigh(c))
{
ops.push(c);
}else{
output.push(c);
}
}
}

//if ([or{
if(isOpen(c))
{
//move operator stack to output stack
while(!ops.empty())
{
output.push(ops.top());
ops.pop();
}
}
}
//put remaining operators on output stack
while(!ops.empty())
{
output.push(ops.top());
ops.pop();
}

//turn output stack into a string


eq = "";
while(!output.empty())
{
eq += output.top();
output.pop();
}
return eq;
}

int main()
{

string eq;

char c;
cin >> eq;
while(eq != "exit")
{
cout << infix2prefix(eq) << endl;
cin >> eq;
}

return 0;
}

S-ar putea să vă placă și