C++ version

  • 개발자 : 나휘동
  • 스택을 이용
  • 문제점 : 연산자가 출력 안 됨
stack.h
~cpp 
#ifndef __STACK__H__
#define __STACK__H__

typedef struct{
	char token;
	int precedence;
}Operator;

const int LEN = 4;

Operator operators[LEN] = {
	{'+', 12},
	{'-', 12},
	{'*', 13},
	{'/', 13}
};

typedef struct{
	Operator op;
}Element;

const int MAX = 10;
Element stack[MAX];
int top = -1;

bool isFull()
{
	return (top < MAX - 1 ? false : true);
}

bool isEmpty()
{
	return (top < 0 ? true : false);
}

Element push(int * top, Element aItem)
{
	if ( *top < MAX - 1 )
		stack[++*top]= aItem;
	return stack[*top];
}

Element pop(int * top)
{
	if ( *top < 0 )
		return stack[*top];
	return stack[--*top--];
}

#endif

main.cpp
~cpp 
#include <iostream.h>
#include <cstring>
#include "stack.h"
void toPostFix(char aTerm[]);
bool isOperand(char aToken);
Operator toOperator(char aToken);
void main()
{
	char term[] = "2*3+4";
	toPostFix(term);
}

void toPostFix(char aTerm[])
{
	int len = strlen(aTerm);
	Element income;
	/*income.op.token = 'b';
	income.op.precedence = 0;
	push(top, income);
	stack[MAX-1].op.token = 'e';
	stack[MAX-1].op.precedence = 100;*/
	for ( int i = 0 ; i < len ; i++ )
	{
		if ( isOperand(aTerm[i]) )
			cout << aTerm[i];
		else{
			income.op = toOperator(aTerm[i]);
			if ( income.op.precedence < stack[top].op.precedence )
				cout << pop(&top).op.token;
			push(&top, income);
		}
	}
	/*while (!isEmpty())
		cout << pop(&top).op.token;*/
}

bool isOperand(char aToken)
{
	for ( int i = 0 ; i < LEN ; i++ )
		if ( operators[i].token == aToken )
			return false;
	return true;
}

Operator toOperator(char aToken)
{
	for ( int i = 0 ; i < LEN ; i++ )
		if ( operators[i].token == aToken )
			return operators[i];
}

Retrieved from http://wiki.zeropage.org/wiki.php/몸짱프로젝트/InfixToPostfix
last modified 2021-02-07 05:29:28