Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef struct {
- int top;
- char container[20];
- }stack ;
- int isempty(stack *s)
- {
- if(s->top==-1)
- {
- return 1;
- }
- else
- return 0;
- }
- void push(stack *s,char x)
- {
- s->container[++s->top]=x;
- printf(" \n pushed %c at %d \n",x,s->top);
- }
- char pop (stack *s)
- {
- if(isempty(s))
- {
- return 0;
- }
- else
- {
- return (s->container[s->top--]);
- }
- }
- int getorder(char op)
- {
- if(op=='(')
- return 0;
- if(op=='-')
- return 1;
- if(op=='+')
- return 2 ;
- if(op=='*')
- return 4;
- if(op=='/')
- return 3;
- }
- int main (){
- char eqn[]="( 10 + 2.5 ) * 4 + 3";
- char *token;
- char token2[1];
- char neweqn[50]=" ";
- stack *s=malloc(sizeof(stack));
- s->top=-1;
- char *ch1;
- token=strtok (eqn," ");
- while(token!=NULL)
- {
- printf("token now is %c \n",token[0]);
- if(token[0]=='+'||token[0]=='-'||token[0]=='/'||token[0]=='*'||token[0]=='(')
- {
- printf("operator %c\n",token[0]);
- if(s->top==-1 ||token[0]=='('|| getorder(token[0])>getorder(s->container[s->top]))
- {
- push(s,token[0]);
- }
- else{
- while(!isempty(s))
- {
- ch1=pop(s);
- if (ch1=='('){break;}
- token2[0]=ch1;
- strcat(neweqn,token2);
- }
- push(s,token[0]);
- }
- }
- else if(!strcmp(token,")"))
- {
- ch1=pop(s);
- printf("popped %c \n",ch1);
- while(ch1!='(')
- {
- token2[0]=ch1;
- strcat(neweqn,token2);
- ch1=pop(s);
- }
- }
- else
- {
- strcat(neweqn,token);
- }
- token=strtok(NULL," ");
- }
- ch1=pop(s);
- token2[0]=ch1;
- strcat(neweqn,token2);
- printf("new eqn .. %s \n",neweqn);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement