簡體   English   中英

C++ 堆棧實現,檢查括號正確性

[英]C++ Stack Implementation, checking parenthesis correctness

我想通過CIN以括號形式給出表達式,例如: ()) 然后,通過堆棧的 push & pop 操作,我希望程序打印我天氣給定的表達式是平衡還是不平衡。 該程序運行良好,但只發現了一個問題,那就是當我輸入 like ()( ,所以它告訴我這個表達式是 IMBALANCED 這很好,但是當我輸入 like () ( ,然后它告訴我這個表達式是平衡的,實際上是不平衡的。

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

char Stack[10];
int top=-1;

void push(char ch)
{
    if(top<10)
    {
        top++;
        Stack[top] = ch;
    }
    else
        cout<<"Stack Overflow";
}

void pop()
{
    if(top > -1)
    {
        top--;
    }
    else
        cout<<"Stack Underflow";    
}
int show(){
    cout<<"It is imbalanced.";
}

int main(int argc, char** argv) 
{
    
    int a=0,b=0;
    string exp;
    cout << "Write down the parenthesis:" ;
    cin >> exp;
    bool check = true;
    
    for(int i=0; i<exp.length(); i++)
    {
        if(exp[i]== '(')
        {
            push(exp[i]);
        }
        else if(exp[i]== ')')
        {
            if(top == -1)
            {
                check = false;
                break;
            }
            else
            {
                pop();
            }
        }
    
    }
    
    for(int i=0; i<exp.length(); i++)
    {
        if(exp[i]=='('){
        ++a;
    }
    else if (exp[i]==')')
    {
        b++;
        
        }   
    }
    
    if(a>b){
        cout<<"\n\nGiven Combination is IMBALANCED";
        return 0;
    }
    
    if(check == true)
        cout<<"\n\nGiven Combination is BALANCED";
    
    else
        cout<<"\n\nGiven Combination is IMBALANCED";
    
    
    return 0;
}

主要評論歸結為:

  • 不需要堆棧時不要使用堆棧。
    • 如果您確實使用了一個,請不要將其限制為任意固定深度。
  • 處理錯誤並報告格式錯誤的表達式。
  • 確保你得到正確的輸入; std::getline()可能比使用>>運算符標記的輸入更不容易出錯。 只需跳過空格(或輸入中允許的任何無關緊要的字符)。
  • using namespace std; 是一種反模式和壞習慣。

基本思想:在遍歷字符串時計算嵌套depth 它最終必須為零。 它在任何時候都不得低於零。

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>
#include <string_view>

using std::size_t;

bool correctly_parenthesized(std::string_view expression) {
  size_t depth{0};
  for (const auto character : expression) {
    switch (character) {
      case '(': ++depth; break;
      case ')': if (depth) { --depth; break; } else { return false; }
      case ' ': break;
      default: throw std::invalid_argument("invalid character");
    }
  }
  return depth == 0;
}

int main() {
  std::cout << "Write down the parenthesis: ";
  std::string exp;
  std::getline(std::cin, exp);
  try {
    std::cout << (correctly_parenthesized(exp) ? "YES" : "NO") << std::endl;
  } catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM