使用堆栈来确定表达式是否具有平衡圆括号
Using a stack to determine if an expression has balanced parentheses
我正在完成本学期的最后一项学校作业,我们是第一次被介绍到堆栈,但我的程序没有正确分析表达式,这让我遇到了问题。一切都在执行,但程序总是产生表达式不平衡的结果。有什么线索可以为我指明正确的方向吗?
//
// main.cpp
// Balanced Parenthesis
#include "StringStack.h"
#include <iostream>
using namespace std;
int main ()
{
StringStack stack;
char entry;
int parCounter = 0;
cout << "This program will accept a string and determine whether it has balanced parenthesis.n";
cout << "Please type a sentence to be analyzedn";
while (cin.get (entry) && entry != 'n')
{
stack.push(entry);
}
if (stack.isEmpty()) {
cout << "The stack is empty./n";
}
else{
stack.pop(entry);
if (entry == ')') {
parCounter++;
}
else if(entry == '('){
parCounter--;
}
}
if (parCounter > 0 || parCounter < 0){
cout << "This expression has UNBALANCED parenthesesn";
}
else
{
cout << "This expression has BALANCED parenthesesn";
}
return 0;
}
// StringStack.h
// Balanced Par
#include <iostream>
using namespace std;
#ifndef StringStack_h
#define StringStack_h
//Define our stack class and its contents
class StringStack
{
private:
char *stackArray;
int stackSize;
char top;
public:
StringStack();
~StringStack() {delete[] stackArray;}
void push(char);
void pop(char &);
bool isBalanced();
bool isEmpty();
};
#endif
//Constructor
StringStack::StringStack()
{
stackArray = new char[stackSize];
top = 0;
}
//Function to determine if stack is empty.
bool StringStack::isEmpty()
{
if (top == 0)
return true;
else
return false;
}
//Function to push letters/puncuation onto the stack
void StringStack::push(char letter)
{
//if (isEmpty())
{
top++;
stackArray[top] = letter;
}
//else
//{
//exit(1);
//}
}
//Function to pop letters/puncuation off the stack
void StringStack::pop(char &letter)
{
if (isEmpty())
{
cout << "The stack is empty.n";
exit(1);
}
else
{
letter = stackArray[top];
top--;
}
}
您没有在任何位置初始化或设置成员stackSize
。这使得new char[stackSize]
的行为没有定义,任何事情都可能发生。
修复后,您只检查堆栈的顶部。您需要一个围绕parCount
的循环来控制if
,直到堆栈为空。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 编写了一个C++代码来检查表达式是否具有平衡括号并且我的代码未运行.我已经卡了一天了
- 使用 vector 检查表达式中的括号是否平衡
- 平衡括号问题为什么要检查它是否为空?
- 使用堆栈来确定表达式是否具有平衡圆括号
- 检查二叉树是否平衡
- STL 映射容器在构造时是否优化(平衡树)
- 我是否应该担心Cassandra c++驱动程序的负载平衡选择?
- 是否允许std::map在只读操作后重新平衡(如Splay树)
- 检测圆括号,括号和大括号是否平衡的c++程序-需要在错误下输出插入符号
- 是否有可能从未排序的数组中高效地创建平衡二叉搜索树而不对数组进行排序?