栈应用之将中缀表达式转化为后缀表达式(逆波兰表达式)

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

#define OK 		1
#define ERROR 		0
#define STACK_INIT_SIZE 20
#define STACK_INCREMENT 10

typedef char Elemtype;
typedef int Status;

typedef struct StackNode{
	Elemtype* base;
	Elemtype* top;
	int stackSize;
}StackNode;
typedef struct StackNode* Stack;

Status InitStack(Stack s){
	s->base = (Elemtype*)malloc(sizeof(Elemtype) * STACK_INCREMENT);
	if(! s->base){
		return ERROR;
	}
	s->top = s->base;
	s->stackSize = STACK_INIT_SIZE;
	return OK;
}
Status Pop(Stack s,Elemtype* value){
	if(s->base == s->top){
		printf("pop ERROR\n");
		return ERROR;
	}
	*value = *(--(s->top));
	return OK;
}
Status Push(Stack s, Elemtype value){
	if(s->top - s->base == s->stackSize){
		s->base = (Elemtype*)realloc(s->base,sizeof(Elemtype) * (STACK_INIT_SIZE + STACK_INCREMENT));
		if(! s->base)
			return ERROR;
		s->top = s->base + STACK_INIT_SIZE;
		s->stackSize = STACK_INCREMENT + STACK_INIT_SIZE;
	}
	*(s->top) = value;
	s->top++;
	return OK;
}
int StackLength(Stack s){
	return s->top - s->base;
} 
//test
Status ShowStack(Stack s){
	while(s->top != s->base){
		printf("%c  ",*(--(s->top)));
	}
	printf("\n");
}

Status Infix2Postfix(){			//将中缀表达式转化为后缀表达式
	StackNode s;
	InitStack(&s);
	char c;
	char c1;
	printf("  Please Enter Infix expression\n");
	printf("  -------note: number separeted by space,end of '#'\n\n");
	scanf("%c", &c);
	/* Note:如果是数字:	直接输出控制台;
	 *      如果是*,/,(: 直接Push
	 *      如果是+,-:    则要将*,/,+,-都进行Pop,直到stack为空或者是遇到了'('
	 *      如果是')':     将在遇到'('之前的所有的都要Pop
	 * */
	while('#' != c){
		while(c >= '0' && c <= '9'){ 	//如果是数字,则直接输出
			printf("%c", c);
			scanf("%c", &c);
			if( c < '0' || c > '9'){
				printf("%c", ' ');
				break;
			}
		}
		if('+' == c || '-' == c){	//如果是 + 或者是 -
			if(!StackLength(&s)){		//如果stack为空的话,直接Push
				Push(&s,c);
			}
			else{			//不为空的话需要Pop进行比较/+-*都需要Pop
				Pop(&s,&c1);
				while( '(' != c1 ){
					printf("%c ", c1);
					if(StackLength(&s) == 0){
						break;
					}
					else
						Pop(&s, &c1);
				}
				if( '(' == c1 )
					Push(&s, c1);
				Push(&s, c);
			}
		}
		else if('*' == c || '/' == c || '(' == c){	//如果是*或者是/
			Push(&s, c);
		}
		else if( ')' == c ){
			Pop(&s,&c1);
			while( '(' != c1){
				printf("%c ", c1);
				Pop(&s, &c1);
			}
		}
		else if( '#' == c ){
			break;
		}
		else{
			printf("Input Is ERROR!\n");
			return ERROR;
		}
		scanf("%c", &c);
	}

	while(StackLength(&s)){
		Pop(&s,&c1);
		printf("%c ", c1);
	}
	return OK;
}
int main(){
	Infix2Postfix();
/*
	Stack s;
	InitStack(s);
	Push(s,'a');
	Push(s,'r');
	Push(s,'e');
	Push(s,'d');
	ShowStack(s);
*/
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值