Stack in the application of the expression process: the establishment of an operand stack and operator stacks. Operators have precedence. Rules:
From the left to the right scan expression, usually encountered operands of the operator stack.
When an operator is encountered, its precedence is higher than the priority of the Fu-top element. Instead, remove the stack top operator and operand stack top two consecutive operands, and the results into the operand stack, and then continue to compare the operator and the stack top operator priority.
The left parenthesis is all in the operator stack, the right parenthesis is not in the operator stack, the operator stack top operator and the operand stack top two operands are counted, and the result is pushed into the operand stack until the left parenthesis is removed.
#include <stdio.h>
#define MAX 100
struct operand
{
int Data[max];
int top;
};
struct OPERATOR_CH
{
int top;
Char Data[max];
};
typedef struct operand opnd;
typedef struct OPERATOR_CH opch;
void Init_opnd_stack (OPND *stack)
{
Stack->top =-1;
}
void Init_opch_stack (opch *stack)
{
Stack->top =-1;
}
void Is_empty_opnd (OPND *stack)
{
if (stack->top = = 1)
{
return-1;
}
return 0;
}
void is_empty_opch (opch *stack)
{
if (stack->top = = 1)
{
return-1;
}
return 0;
}
int Get_opnd_top (OPND *stack)
{
if (IS_EMPTY_OPND (stack) = = 1)
{
return-1;
}
Return stack->data[stack->top];
}
int Get_opch_top (opch *stack)
{
if (is_empty_opch (stack) = = 1)
{
return-1;
}
Return stack->data[stack->top];
}
int PUSH_OPND (OPND *stack, int num)
{
stack->data[++ (stack->top)] = num;
}
int push_opch (opnd *stack, Char ch)
{
stack->data[++ (stack->top)] = ch;
}
int POP_OPND (OPND *stack)
{
if (IS_EMPTY_OPND (stack) = = 1)
{
return-1;
}
int num = stack->data[stack->top];
(stack->top)--;
return num;
}
Char pop_opch (opch *stack)
{
if (is_empty_opch (stack) = = 1)
{
return-1;
}
char ch = stack->data[stack->top];
(stack->top)--;
return ch;
}
int get_priority (char ch)
{
if (ch = = ' + ' | | | ch = = '-')
{
return 1;
}
if (ch = = ' * ' | | ch = = '/')
{
return 2;
}
}
int compare_priority (char op_ch, Char ch)
{
if (get_priority (op_ch) > get_priority (CH))
{
return 1;
}
return-1;
}
int count (int num1, int num2, char ch)
{
int result;
Switch (CH)
{
Case ' + ':
{
result = a + B;
Break
}
Case '-':
{
result = A-b;
Break
}
Case ' * ':
{
result = A * b;
Break
}
Case '-':
{
result = A/b;
Break
}
}
return result;
}
int main ()
{
Char ch;
Char op_ch;
while (ch = getchar ())!= ' \ n ')
{
if (ch >= ' 0 ' && ch <= ' 9 ')
{
Push_stack1 ();
}
if (ch = = ' + ' | | | ch = = ' | | ch = = ' * ' | | ch = = '/')
{
Op_ch = Pop_stack2 ();
if (compare (Op_ch,ch) > 0)
{
Push_stack2 (CH);
}
Else
{
Count (A,b,op_ch);
}
}
}
return 0;
}