Rso's Jotter

日々の開発の知見のメモやその他雑記

逆ポーランド変換プログラム

数式を逆ポーランド記法に変換する。
調子のってC++あんま知らんのに書いたので冗長になった。

#define STACKSIZE 100

#include  
using namespace std;

class stack {
	char data[100];		//データ
	int sp;				//スタックポインタ
public:	
	stack(){			//コンストラクタ
	sp = 0;
	data[0] = 0;	//番兵
	}
	void push(char);	//プッシュ
	char pop();			//ポップ
	char get(){			//スタックポインタの指すデータを返す
		return data[sp];
	}
	int getsp(){		//スタックポインタの値(添字)を返す
		return sp;
	}
	void outputch();	//文字の出力
	
};

void stack::push(char c)
{
	if(sp == STACKSIZE){
		cout << "スタックオーバーフロー" << endl;
		exit(-1);
	}
	//	cout << c << " push" << endl;	//動作確認用
	data[++sp] = c;
}

char stack::pop(){
	if(sp){
	//	cout << data[sp] << " pop" << endl;	//動作確認用
		return data[sp--];
	}
	else
		cout << "ERROR" << endl;
		exit(-1);
		return 0;
}

void stack::outputch(){
	
	for(int i =1;i <= sp;i++)
		cout << data[i];

	cout << endl;
}


int main()
{
	int pri[255];
	
	for(int i=0;i < 255;i++)
		pri[i] = 3;

	pri[0] = -1;	//番兵は優先順位は最低
	pri['+'] = pri['-'] = 1;
	pri['*'] = pri['/'] = 2;
	pri['('] = 4,pri[')'] = 0;

	char expression[] = "(a+b)*c+d";	//変換する元の文字列
	char *p = expression;
	stack result,work;

	while(*p != '\0')
	{
		

		while(pri[*p] <= pri[work.get()] && work.get() != '(' )
			result.push(work.pop());

		if(*p == ')'){
			work.pop();	//開き括弧を捨てる
			p++;
		}
		else{
		work.push(*p++);
		}
	}

	for(int i=work.getsp() ; i > 0;i--)	//workスタックの残りの分をすべてresultへプッシュ
		result.push(work.pop());

	result.outputch();

	return 0;
}