Hey guys, I'm having much difficulties with a problem from my C book. The problem asks you to convert an infix notation, such as "1 + 2" to the more computer friendly postfix, "1 2 +". I tried with the algorithm that my book supplied to me but my program keeps crashing. Here's what i have so far:
Thanks for any help guys.Code:#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define LENGTH(x) ( sizeof(x) / sizeof(x[0]) ) typedef struct node{ char data; struct node *next; } Node; void push( Node **sHead, char value ); char pop( Node **sHead ); int isEmpty( Node *head ); void printS( Node *s ); char stackTop( Node *s ); void convertInToPost( Node **sHead, char *infix, char *postfix ); void strchar( char *str, char c ); int isOperator( char c ); int precedence( char op1, char op2 ); int main( void ){ Node *head = NULL; char infix[] = "1+2"; char postfix[10]; postfix[0] = '\0'; convertInToPost( &head, infix, postfix ); printf( "%s ", postfix ); return 0; } // main void convertInToPost( Node **sHead, char *infix, char *postfix ){ int i; push( sHead, '(' ); strncat( infix, ")", 1 ); while( !isEmpty( *sHead ) ) for( i = 0 ; i < LENGTH( infix ) ; i++ ) if( isdigit(infix[i]) ) strchar( postfix, infix[i] ); else if( infix[i] == '(' ) push( sHead, infix[i] ); else if( isOperator( infix[i] ) ){ if( precedence( stackTop( *sHead ), infix[i] ) >= 0 ) strchar( postfix, pop( sHead ) ); push( sHead, infix[i] ); }else if( infix[i] == ')' ){ while( stackTop( sHead ) != '(' ) strchar( postfix, pop( sHead ) ); pop( sHead ); } } // convertIntoPost void strchar( char *str, char c ){ while( *str != '\0' ) str++; *str = c; *(str + 1 ) = '\0'; } // strchar int isOperator( char c ){ if( c == '*' || c == '/' || c == '+' || c == '-' ) return 1; return 0; } // isOperator int precedence( char op1, char op2 ){ switch( op1 ){ case '*': case '/': if( op2 == '*' || op2 == '/' ) return 0; else return 1; case '+': case '-': if( op2 == '*' || op2 == '/' ) return -1; else return 0; } return -10; } // precedence char stackTop( Node *s ){ if( !isEmpty( s ) ) return s->data; return '\0'; } // stackTop void printS( Node *s ){ while( !isEmpty( s ) ){ printf( "%3c --> ", s->data ); s = s->next; } printf( "NULL\n\n" ); } // printS void push( Node **sHead, char value ){ Node *newNode; newNode = malloc( sizeof( Node ) ); if( newNode != NULL ){ newNode->data = value; newNode->next = *sHead; *sHead = newNode; }else printf( "***ERROR*** Could _NOT_ allocate memory for new object!\n" ); } // push char pop( Node **sHead ){ Node *temp; char value; if( !isEmpty( *sHead ) ){ value = (*sHead)->data; temp = *sHead; *sHead = (*sHead)->next; free( temp ); return value; } return '\0'; } // pop int isEmpty( Node *head ){ return head == NULL; } // isEmpty
Dat



LinkBack URL
About LinkBacks



CornedBee