1
我不知道我在哪裏做錯了。每次在主功能結束時「流行」它總是沒有給我任何東西。每次在手術後推進,我都會檢查一下,結果就在那裏。但是每次我在for循環外彈出時,棧都沒有給我任何東西。謝謝之前,我非常感謝你的回答。 P.S =我不允許使用類或OOP。所以請不要用這些方法給我答案。使用堆棧和C++字符數組評估Postfix表達式
#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中的腳本,但如果我添加彈出到它,它不會改變任何東西。 –
然後請將問題中的代碼編輯爲您實際遇到問題的代碼。 –