#include #include #include #include int debug = 1; typedef struct cell{ int item; struct cell *next; } cell; typedef cell *list; list stk; void push(int x){ list p = (list)malloc(sizeof(cell)); p->item = x; p->next = stk; stk = p; } int pop(){ int x; list next; if(stk == NULL){ fprintf(stderr, "スタックが空になっています\n"); return 0; } x = stk->item; next = stk->next; free(stk); stk = next; return x; } int top(){ return stk->item; } void print_stack(){ static list pstk; static int depth = 0; if(depth == 0){ pstk = stk; printf("スタックの中身:"); } list current = pstk; if(current != NULL){ pstk = pstk->next; depth++; print_stack(); depth--; printf(" %d", current->item); } if(depth == 0) printf("\n"); } int main(int argc, char *argv[]){ int head, next; char *input; if(argc <= 1){ fprintf(stderr, "##### コマンドライン引数で逆ポーランド記法を入力してください\n"); return 1; } input = argv[1]; for(head = 0; head < strlen(input); head = next+1){ next = head; while(input[next] != ' ' && input[next] != '\0')next++; if(isdigit(input[head])){ int num; sscanf(&input[head], "%d", &num); if(debug) printf("<- %d (数値)\n", num); push(num); } else{ int num1, num2, answer; switch(input[head]){ case '+': if(debug) printf("<- '+' (演算子)\n"); num1 = pop(); num2 = pop(); answer = num2 + num1; push(answer); break; case '-': if(debug) printf("<- '-' (演算子)\n"); num1 = pop(); num2 = pop(); answer = num2 - num1; push(answer); break; case '*': if(debug) printf("<- '*' (演算子)\n"); num1 = pop(); num2 = pop(); answer = num2 * num1; push(answer); break; case '/': if(debug) printf("<- '/' (演算子)\n"); num1 = pop(); num2 = pop(); answer = num2 / num1; push(answer); break; default: fprintf(stderr, "##### '%c' は未知の演算子です\n", input[head]); } } if(debug) print_stack(); } printf("答え %d\n", top()); return 0; }