我不知道我哪里做错了。每次我在 main 函数的末尾“弹出”它总是什么也没给我。我在每次操作后推送之前和之后都通过弹出来检查,结果就在那里。但是每次我跳出 for 循环时,堆栈什么也没给我。之前谢谢,非常感谢您的回答。PS = 我不允许使用类或 OOP。所以请不要用这些方法给我答案。
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<cstdlib>
#include<cstring>
using namespace std;
typedef struct
{
int top;
int data[20];
}stack;
void initStack(stack &S)
{
int i;
S.top=-1;
}
int pop (stack &S)
{
int number;
number = S.data[S.top];
S.top = S.top - 1;
return number;
}
void push(stack &S, int number)
{
S.top = S.top + 1;
S.data[S.top] = number;
}
void compute(stack &S, char *ch, int n)
{
int result;
for (int i = 0 ; i <= n-1; i++)
{
if (ch[i] == '*')
{
int operand1 = pop (S);
int operand2 = pop (S);
result = operand1 * operand2;
push(S, result);
}
else if (ch[i] == '/')
{
int operand1 = pop (S);
int operand2 = pop (S);
result = operand1 / operand2;
push(S, result);
}
else if (ch[i] == '+')
{
int operand1 = pop (S);
int operand2 = pop (S);
result = operand1 + operand2;
push(S, result);
}
else if (ch[i] == '-')
{
int operand1 = pop (S);
int operand2 = pop (S);
result = operand1 - operand2;
push(S, result);
}
else
{
result = ch[i] - '0';
push(S, result);
}
}
}
main()
{
stack ST;
char ch[20];
initStack(ST);
cout<<"Please enter the operation: ";
gets(ch);
int n = strlen(ch);
compute(ST, ch, n);
pop(ST);
}