プログラミング演習2 課題1 問題3 逆ポーランド記法リストで作る by 아즈마

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int debug=1;

typedef struct list {
int item;
struct list *next;
} list;

list *stk;

int emptystack() { /* スタックが空かどうかの判定 */
if ( stk == NULL ) return 1;
return 0;
}

void initstack() { /* スタックを初期化 */
stk = NULL;
}

void push( int x ) { /* スタックにxを追加 */
list *p = (list *)malloc(sizeof( list)); /* C言語では malloc 領域を確保 */
p->item = x;
p->next = stk;
stk = p;
}

int pop() { /* スタックからデータを取得 */
int x;
list *next;
if(emptystack() ) {
fprintf( stderr, "#### スタックが空になっています\n");
return 0;
}
x = stk->item;
next = stk->next;
free(stk); /* 教科書と違い、実際には malloc した領域を解放 */
stk = next;
return x;
}

int top() { /* スタックからデータを取得 */
return stk->item;
}


void print_list(){
    list *i;
    i=stk;
    printf("リストの中身: ");
    for(i; i!=NULL; i=i->next){
    printf("% d", i->item);
    }
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++;/* 空白 or 文字列の未尾を探す */

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_list();
}
printf("答え %d\n", top());

return 0;
}

트랙백

이 글과 관련된 글 쓰기 (트랙백 보내기)
TrackbackURL : http://ldh21.egloos.com/tb/2470871 [도움말]

덧글

덧글 입력 영역