堆栈计算器(Stack calculator).docVIP

  • 10
  • 0
  • 约 11页
  • 2017-10-06 发布于河南
  • 举报
堆栈计算器(Stack calculator)

堆栈计算器(Stack calculator) 1. Define the stack structure of the postfix calculator Because there are not many units to store, a sequential stack is used here, that is, to simulate the stack with a one-dimensional array: #define MAX 100 Int stack[MAX]; Int top=0; Therefore, the program defines a one-dimensional array of length MAX, where MAX is defined as constant 100 by macro, and we can modify the macro definition to redefine the size of the stack. The integer data top indicates to the top of the stack that the top is initialized to 0 because there is no data element in the stack at the beginning of the program. 2, store the number of postfix calculator After we have defined the stack stack[MAX], we can use the stack operation to store two operands entered successively. Heres how it works: Int push (int i) / * memory operand, stack operation. { If (top, MAX) { There is still room for stack[++top]=i; / * stack, the stack indicates a shift position * / Return 0; } Else / * stack is full, giving the wrong information, return an error indication. { Printf (The stack is full); Return ERR; } } When we call the function push, if its return value is 0, the stack operation is successful; otherwise, if the return value is ERR (specified in the program as -1), the stack operation fails. 3. Take out operands from the stack When the four operator has been read in the program, we can take out two operands that have been saved from the stack, form an expression, and calculate the result. The algorithm that extracts the operand is the stack algorithm. In this case, the function to implement the algorithm is pop (): Int (POP); / * remove the operand stack, * / { Int VaR; / * defined to return the top of the stack. If (top! =NULL) there are data elements / * stack { Var=stack[top--]; / * * / a position indicator down stack Return var; } Else / * stack is empty, an error message, and returns the return value. Printf (The, stack, is, cmpty, \n); Return ERR; } Similarly, if the stack is n

文档评论(0)

1亿VIP精品文档

相关文档