ALDS1_3_A: Stack

この問題は『プログラミングコンテストのためのアルゴリズムとデータ構造(渡部有隆著,Ozy・秋葉拓哉協力)』を読んで解きました.

 

問題

 

ソースコード

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

int value[100];
int sp = 0;

void push(const int val)
{
    value[sp++] = val;
}

int pop()
{
    return value[--sp];
}

void operand(const char operand)
{
    int ch, val = operand - '0';
    while( (ch = getchar()) != ' ' ){
        val = val * 10 + (ch - '0'); 
    }
    push(val);
}

void operator(const char operator)
{
    int tmp1 = pop(), tmp2 = pop();

    switch( operator ){
    case '+': push(tmp2 + tmp1); break;
    case '-': push(tmp2 - tmp1); break;
    case '*': push(tmp2 * tmp1); break;
    default : break;
    }
}

int main()
{
    while( 1 ){
        int ch = getchar();
        if( ch == ' ' || ch == '\n' ) continue;
        if( ch == EOF ) break;
        
        switch( ch ){
        case '+': case '-': case '*': operator(ch); break;
        default : operand(ch); break;
        }
    }

    printf("%d\n", pop());

    return 0;
}

 

反省点

  • 演算子'-'の場合,push(pop() - pop())としていたらサンプルが通らない
  • push(-pop() + pop())としても通らない
  • 演算子'+', '*'は可換なのでオペランドをpop()してから演算することにした(pop()(second) (operator) pop()(first))
  • 2桁以上のオペランドを1桁ずつ扱っていたのでWA
  • オペランドの場合,while文でスペースまで取得
  • scanfで扱う方法を知りたい(scanfではEOFが扱えず,無限ループに陥ってSegmentation faultで死亡する)