[code=C/C++][/code]
#include <stdio.h>
typedef int ElemType;
#define MAXNUM 16
struct stack
{
ElemType data[MAXNUM];
int top;
};
void StackInit(struct stack *stack)
{
int i = 0;
for(;i < MAXNUM;i++)
{
stack->data[i] = 0;
}
stack->top = 0;
}
void StackPush(struct stack *stack,ElemType c)
{
if(MAXNUM == stack->top)
{
printf("The stack is full ");
return;
}
stack->data[stack->top++] = c;
}
ElemType StackPop(struct stack *stack)
{
if(0 == stack->top)
{
printf("The stack is empty ");
return 0;
}
return stack->data[--stack->top];
}
void Postfixevaluation(struct stack *stack)
{
return;
}
int ChangeToPostfix(char *str)
{
int i = 0,flag = 0;
int c,ch;
struct stack ch_stack;
struct stack op_stack;
StackInit(&ch_stack);
StackInit(&op_stack);
while( != (c = *(str + i)))
{
if((* == c) || (/ == c) || (( == c))
{
flag = 0;
StackPush(&op_stack,c);
}
else if() == c)
{
flag = 0;
while(( != (c = StackPop(&op_stack)))
{
StackPush(&ch_stack,c);
}
if(0 == op_stack.top)
{
printf("the ( hasnt found when the ) come in! ");
return -1;
}
}
else if((+ == c)|| (- == c))
{
flag = 0;
if(0 != op_stack.top)
{
while(( != (ch = StackPop(&op_stack)))
{
StackPush(&ch_stack,ch);
if(0 == op_stack.top)
{
break;
}
}
}
StackPush(&op_stack,c);
}
else if((c >= 0) && (c <= 9))
{
if(0 == flag)
{
StackPush(&ch_stack,(c - 0));
flag = 1;
}
else
{
StackPush(&ch_stack,10 * StackPop(&ch_stack) + (c - 0));
}
}
i++;
}
while(0 != op_stack.top)
{
StackPush(&ch_stack,StackPop(&op_stack));
}
Postfixevaluation(&ch_stack);
for(i = 0;i < ch_stack.top;i++)
{
if(+ == ch_stack.data[i])
{
printf("+..");
}
else if(- == ch_stack.data[i])
{
printf("-..");
}
else if(* == ch_stack.data[i])
{
printf("*..");
}
else if(/ == ch_stack.data[i])
{
printf("/..");
}
else
{
printf("%d..",ch_stack.data[i]);
}
}
return 0;
}
int main(void)
{
char str[] = "12 + 34 * 435 - 5 / 1";
printf("The result should be : ");
printf("12 34 435 * + 5 1 / - [= 8] ");
if(-1 == ChangeToPostfix(str))
{
printf("ChangeToPostfix() error ");
return 1;
}
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)