简体   繁体   English

C++ 堆栈实现,检查括号正确性

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

I want to give the expression in the form of parenthesis through CIN, like: ()) .我想通过CIN以括号形式给出表达式,例如: ()) then, through push & pop operation of the stack, I want the program to print me weather the given expression is BALANCED or NOT.然后,通过堆栈的 push & pop 操作,我希望程序打印我天气给定的表达式是平衡还是不平衡。 The program works perfectly but only one issue has been found & that is when I enter like ()( , so it tells me that this expression is IMBALANCED which is fine but when I enter like () ( , so then it tell me that this expression is BALANCED which is actually not balanced.该程序运行良好,但只发现了一个问题,那就是当我输入 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;
}

The main comments boil down to:主要评论归结为:

  • Don't use a stack when no stack is needed.不需要堆栈时不要使用堆栈。
    • And if you do use one, don't limit it to an arbitrary fixed depth.如果您确实使用了一个,请不要将其限制为任意固定深度。
  • Handle errors and report malformed expressions.处理错误并报告格式错误的表达式。
  • Make sure you get the right input;确保你得到正确的输入; std::getline() may be less error-prone than input tokenized using the >> operators. std::getline()可能比使用>>运算符标记的输入更不容易出错。 Just skip spaces (or whatever insignificant characters are allowed in the input).只需跳过空格(或输入中允许的任何无关紧要的字符)。
  • using namespace std; is an antipattern and a bad habit.是一种反模式和坏习惯。

The basic idea: Calculate the nesting depth as you iterate over the string.基本思想:在遍历字符串时计算嵌套depth It must be zero, ultimately.它最终必须为零。 It must not drop below zero at any point.它在任何时候都不得低于零。

#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