Exemplo n.º 1
0
void ConvToRPNExp(char exp[LEN])
{
	Stack stack;
	int expLen = strlen(exp);
	char convExp[LEN];

	int i, idx = 0;
	int flag_d = 0;
	char tok, popOp;
	
	StackInit(&stack);

	for(i=0; i<expLen; i++)
	{
		tok = exp[i];
		if (isdigit(tok)){
			convExp[idx++] = tok;
		}
		else if (tok == '.'){
			convExp[idx++] = tok;
		}
		else
		{
			convExp[idx++] = ' ';
			switch(tok)
			{
			case '(':
				SPush(&stack, tok);
				break;

			case ')':
				while(1)
				{
					popOp = SPop(&stack);
					if(popOp == '(')
						break;
					convExp[idx++] = popOp;
				}
				break;

			case '+': case '-': 
			case '*': case '/':
				while(!SIsEmpty(&stack) && 
						WhoPrecOp(SPeek(&stack), tok) >= 0)
					convExp[idx++] = SPop(&stack);

				SPush(&stack, tok);
				break;
			}
		}
	}

	while(!SIsEmpty(&stack))
		convExp[idx++] = SPop(&stack);

	convExp[idx] = '\0';

	strcpy(exp, convExp);
}
char* ConvToRPNExp(char exp[]){
	Stack stack;
	int expLen=strlen(exp);
	char *conv=(char*)malloc(sizeof(char)*expLen*2+1);
	Conv convExp;
	Value *print;
	int i,j=0;
	char tok,tokTmp,popOp;
	char *addStr=(char*)malloc(sizeof(char)*30);
	int tmpDigit=0;

	memset(conv,0,sizeof(char)*expLen*2+1);
	LBStackInit(&stack);
	convExp.head=convExp.cur=NULL;
	convExp.num=0;
	
	for(i=0;i<expLen;i++){
		if(isdigit(tok=exp[i])){
			while(isdigit(tokTmp=exp[i+(j++)])){
				tmpDigit*=10;
				tmpDigit+=(tokTmp-'0');
			}

			if(convExp.head==NULL) headSet(&convExp);
			else addValue(&convExp);

			convExp.cur->digit=tmpDigit;

			i+=j-2;
			tmpDigit=j=0;
		}
		else{
			switch(tok){
				case '(':
					LBSPush(&stack,tok);
					break;
				case ')':
					while(1){
						popOp=LBSPop(&stack);
						if(popOp=='(') break;
						addValue(&convExp);
						convExp.cur->operator[0]=popOp;
					}
					break;
				case '+':case '-':
				case '*':case '/':
					while(!LBSIsEmpty(&stack) && WhoPrecOp(LBSPeek(&stack),tok) >=0){
						addValue(&convExp);
						convExp.cur->operator[0]=LBSPop(&stack);
					}
					LBSPush(&stack,tok);
					break;
			}
		}
	}
	while(!LBSIsEmpty(&stack)){
		addValue(&convExp);
		convExp.cur->operator[0]=LBSPop(&stack);
	}

	print=convExp.head;

	for(i=0;print!=NULL;i++){
		if(print->operator[0]!=0) strcat(conv,print->operator);
		else{
			itoa(print->digit,addStr,10);
			strcat(conv,addStr);
		}
		strcat(conv," ");
		print=print->next;
	}
	conv[strlen(conv)-1]=0;
	return conv;
}