【发布时间】:2013-10-11 10:58:29
【问题描述】:
我不知道我哪里做错了。每次我在 main 函数的末尾“弹出”它总是什么也没给我。我在每次操作后推送之前和之后都通过弹出来检查,结果就在那里。但是每次我跳出 for 循环时,堆栈什么也没给我。之前谢谢,非常感谢您的回答。 P.S = 我不允许使用类或 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);
}
【问题讨论】:
-
你从来没有真正“弹出”
main函数,也没有打印任何东西,那么你怎么知道有问题? -
我不小心忘记了在stackoverflow中编写的脚本中弹出,但是如果我将弹出添加到其中,它不会改变任何东西。
-
那么请将问题中的代码编辑为您实际遇到问题的代码。
-
好的,我已经编辑了代码。之前感谢您的回复:)
标签: c++ arrays char stack postfix-notation