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

#include
#include

#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;
}

你可能感兴趣的:(数据结构)