2013-10-04 59 views
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); 
} 
+0

你從來沒有真正在「main」函數中「彈出」,也沒有打印任何東西,所以你怎麼知道有問題? –

+0

我意外地忘了彈出在我寫在stackoverflow中的腳本,但如果我添加彈出到它,它不會改變任何東西。 –

+0

然後請將問題中的代碼編輯爲您實際遇到問題的代碼。 –

回答

1

那麼如果我理解正確的話,這個問題是非常簡單的。您需要打印的價值,你如雨後春筍般冒出

更換

pop(ST); 

cout << pop(ST) << '\n'; 

顯然,你不會看到任何東西,除非你還記得你打印希望看到的。

+0

我想我太專注於算法,然後我忘了添加cout,現在它工作。非常感謝 :) –