Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #define TYPE int
- #define STACKSIZE 100
- typedef struct {
- int top;
- TYPE items[STACKSIZE];
- } Stack;
- void initialize(Stack *s) {s->top=0;}
- void push(Stack *s,TYPE value) {s->items[s->top++]=value;}
- TYPE pop(Stack *s) {return s->items[--s->top];}
- TYPE peek(Stack *s) {return s->items[s->top-1];}
- int isfull(Stack *s) {return s->top<STACKSIZE?0:1 ;}
- int isempty(Stack *s) {return s->top==0?1:0;}
- void error() {printf("error");exit(-1);}
- int isoperator(char e)
- {
- if(e == '+' || e == '-' || e == '*' || e == '/' || e == '%') return 1;
- 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){
- char *i,*p;
- Stack X; char n1;
- initialize(&X);
- i = infix;
- p = postfix; //&postfix[0];
- while(*i){
- while(*i == ' ' || *i == '\t')
- i++;
- if( isdigit(*i) || isalpha(*i) ) {
- while( isdigit(*i) || isalpha(*i)){
- *p = *i;
- p++;
- i++;
- }
- *p++ = ' ';
- }
- if( *i == '(' )
- push(&X,*i++);
- if( *i == ')'){
- n1 = pop(&X);
- while( n1 != '(' ){
- *p++ = n1;
- *p++ = ' ';
- 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++ = ' ';
- n1 = pop(&X);
- }
- push(&X,n1);
- push(&X,*i);
- }
- i++;
- }
- }
- while(!isempty(&X)){
- n1 = pop(&X);
- *p++ = n1;
- *p++ = ' ';
- }
- *p = '\0';
- }
- int main()
- {
- Stack s; initialize(&s);
- // Input: (((8 + 1) - (7 - 4)) / (11 - 9))
- // Output: 8 1 + 7 4 - - 11 9 - /
- char inStr[100];
- strcpy(inStr,"(((8 + 1) - (7 - 4)) / (11 - 9))");
- char post[100];
- infix2postfix(inStr,post);
- printf("%s<-->%s\n",inStr,post);
- strcpy(inStr,"a+b/c");
- infix2postfix(inStr,post);
- printf("%s<-->%s\n",inStr,post);
- strcpy(inStr,"a/b+c");
- infix2postfix(inStr,post);
- printf("%s<-->%s\n",inStr,post);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment