スタックでは、中式を拡張式に変換します.(逆ポーランド式)
3133 ワード
#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
");
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("
");
}
Status Infix2Postfix(){ //
StackNode s;
InitStack(&s);
char c;
char c1;
printf(" Please Enter Infix expression
");
printf(" -------note: number separeted by space,end of '#'
");
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!
");
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;
}