#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define MAX_STACK_SIZE 100
typedef char element;
typedef struct{
element stack[MAX_STACK_SIZE];
int top;
} StackType;
void init(StackType *s) {
s->top = -1;
}
int is_empty(StackType *s){
return (s->top == -1);
}
int is_full(StackType *s){
return (s->top==(MAX_STACK_SIZE-1));
}
void push(StackType *s, element item){
if(is_full(s)){
fprintf(stderr,"스택포화에러\n");
return;
}
else s->stack[++(s->top)]=item;
}
element pop(StackType *s){
if(is_empty(s)){
fprintf(stderr,"스택공백에러\n");
exit(1);
}
else return s->stack[(s->top)--];
}
element peek(StackType *s){
if(is_empty(s)){
fprintf(stderr,"스택공백에러\n");
exit(1);
}
else return s->stack[s->top];
}
int prec(char op) {
switch(op){
case '(': case ')': return 0;
case '+': case '-': return 1;
case '*': case '/': return 2;
}
return -1;
}
void infix_to_postfix(char exp[], char res[]) {
int i=0, j=0;
char ch, top_op, cx;
int len = strlen(exp);
StackType s;
init(&s);
for(i=0; i<len; i++){
ch = exp[i];
switch(ch){
case '+': case '-': case '*': case '/':
while( !is_empty(&s) && (prec(ch) <= prec(peek(&s)))) {
printf("%c",cx=pop(&s));
res[j++]=cx;
}
push(&s, ch);
break;
case '(':
push(&s, ch);
break;
case ')':
top_op = pop(&s);
while( top_op != '('){
printf("%c", top_op);
res[j++]=top_op;
top_op = pop(&s);
}
break;
default:
printf("%c", ch);
res[j++]=ch;
break;
}
}
while( !is_empty(&s)) {
printf("%c", cx=pop(&s));
res[j++]=cx;
}
}
int eval(char exp[]) {
int op1, op2, value, i=0;
int len = strlen(exp);
char ch;
StackType s;
init(&s);
for(i=0;i<len;i++)
if('0'<=exp[i]&&exp[i]<='9')
exp[i]=exp[i]-'0';
for( i=0; i<len; i++){
ch = exp[i];
if( ch != '+' && ch != '-' && ch != '*' && ch != '/'){
push(&s, ch);
}
else{
op2 = pop(&s);
op1 = pop(&s);
switch(ch){
case '+': push(&s,op1+op2); break;
case '-': push(&s,op1-op2); break;
case '*': push(&s,op1*op2); break;
case '/': push(&s,op1/op2); break;
}
}
}
return pop(&s);
}
int main() {
char res[100]={0,};
int result;
infix_to_postfix("(2+3)*4+9", res);
result = eval(res);
printf("\n");
printf("결과값은 %d\n", result);
return 0;
}
'c·c++ > c 프로그래밍' 카테고리의 다른 글
간단한 연결리스트 (0) | 2013.10.28 |
---|---|
n보다 작은 소수 출력하기 (0) | 2013.10.26 |
파일 expand (0) | 2013.10.25 |
가우스 조던 소거법 (0) | 2013.10.20 |
10진수를 2진수, 8진수, 16진수로 (0) | 2013.10.16 |