【发布时间】:2021-12-11 21:28:23
【问题描述】:
我想通过CIN以括号的形式给出表达式,例如:())。然后,通过堆栈的 push & pop 操作,我希望程序打印给我的天气给定的表达式是 BALANCED 还是 NOT。该程序运行良好,但只发现了一个问题,那就是当我输入 ()( 时,它告诉我这个表达式是 IMBALANCED 这很好,但是当我输入 () ( 时,它告诉我这个表达式是 BALANCED,实际上是不平衡的。
#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;
}
【问题讨论】:
-
你不想检查检查是否为真,堆栈是否为空,看看它是否平衡,否则它是不平衡的。我认为您计数 ( 和 ) 的结束循环不是正确的解决方案。
-
这个计算不需要栈。
-
那么,添加一个
else分支以跳过空格。 -
() (的错误是cin >> exp;请记住,cin >> exp;会读取到第一个空格字符,因此当您键入() (时,您只会读取平衡的()。起初我没有看到,但在这里调试:https://onlinegdb.com/pji0k1cHZS 并在第 50 行放置断点并添加() (作为输入文本后几秒钟内看到它。
标签: c++ data-structures stack push parentheses