전체자료 2개
-
-
[자료구조론] 사칙연산에서 infix의 postfix로의 변환
-
..FILE:POSTFIX.hwp#include #include #include #define MAX 100/* 스택의 최대 크기 설정 */int stack[MAX];int top;void init_stack(void){top = -1;}int push(int val){if(top >= MAX - 1){printf("n Stack overflow.");exit(1);}stack[++top] = val;return val;}/* 스택의 값을 팝 */int pop(void){if(top < 0){printf("n Stack underflow.");exit(1);}return stack[top--];}/* 스택의 값을 참조*/int get_stack_value(void){return (top < 0) ? -1 : stack[top];}/* 스택 empty 검사 */int is_stack_empty(void){return (top < 0);}/* stack에서 pop의 시점을 정하기 위한 연산자 우선순위 부여 함수 */int check_order(int oper){if(oper == '(') return 0;else if(oper == '+' || oper == '-') return 1;else if(oper == '*' || oper == '/') return 2;else return 3;}/* check_error()함수 에서 digit_count변수 카운트시 1자리수 이상의 수 입력으로인한 잘못된 카운트 입력을 막고 하나의 수로 취급하기 위해 체크하는 함수 */char *check_digit(char *in_exp){while(isdigit(*in_exp)){in_exp++;}return --in_exp;}void postfix(char *src_exp, char *dst_exp){init_stack();while(*src_exp){if(*src_exp == '('){push(*src_exp);src_exp++;}else if(*src_exp == ')'){ >= check_order(*src_exp)){*dst_exp++ = pop(); /* 연산자를 만나면 우선순위기 낮은 연산자를 */*dst_exp++ = ' '; /* 만날 때까지 pop한다. */}push(*src_exp);src_exp++;}else if(isdigit(*src_exp)){ /* 숫자는 그대로 출력 */do{*dst_exp++ = *src_exp++;}while(isdigit(*src_exp));*dst_exp++ = ' ';}elsesrc_exp++;}while(!is_stack_empty()){*dst_exp++ = pop();*dst_exp++ = ' ';}dst_exp--;*dst_exp = 0;}int calculate(char *post_exp){int val; /* 연산결과 저장 */init_stack(); /* 스택의 초기화 */while(*post_exp){if(isdigit(*post_exp)){val = 0;do{val = val*10 + *post_exp - '0';/*한자리 이상의 수 입력대비 */post_exp++;}while(isdigit(*post_exp));push(val);}else if(*post_exp == '+'){ /* 연산 순서를 생각해야하는 -, /는 */push(pop() + pop()); /* val 변수 이용 */}else if(*post_exp == '*'){push(pop() + pop());}else if(*post_exp == '-'){val = pop();push(pop() - val);}else if(*post_exp == '/'){val = pop();push(pop() / val);}else;post_exp++;}return pop();}/*잘못된 입력에 대한 에러 체크함수*/void error_check(char *in_exp){int digit_count=0, oper_count=0, left_brace_count=0, right_brace_count=0;/* 피연산자 연+' || *in_exp == '-' || *in_exp == '/' || *in_exp == '*'){oper_count++;}else if(*in_exp == ' ');else{printf("수식내 잘못된 문자 입력에 의한 오류입니다.n다시 시도하세요.n");exit(0);}}while(*(in_exp++) == '