【问题标题】:balances brackets problem(always the output is good)平衡括号问题(总是输出很好)
【发布时间】:2020-03-29 17:46:15
【问题描述】:

我必须编写一个用括号平衡字符串的程序。我编写了程序,但输入哪个字符串并不重要,因为程序总是说字符串是好的。 代码如下:

头文件

#ifndef HEADER_H_
#define HEADER_H_
#include <string>

struct Element {
    char data;
    Element* link;
};

typedef Element* Stack;

void initStack(Stack& S);
void push(Stack& S, int a);
void pop(Stack &S);
int top(Stack& S);
bool isEmpty(Stack &S);
bool goodPair(char deschis, char inchis);
bool check(std::string s);

#endif

函数文件

#include <iostream>
#include <string>
#include "header.h"
using namespace std;

void initStack(Stack& S)
{
    S = nullptr;
}

void push(Stack& S, int a)
{
    Element*nou = new Element;
    nou->data = a;
    nou->link = S;
    S = nou;
}

void pop(Stack& S)
{
    Stack aux = S;
    S = S->link;
    delete(aux);
}

int top(Stack& S)
{
    if (isEmpty(S))
        return int();
    return S->data;
}

bool isEmpty(Stack &S)
{
    if (S == 0)
        return true;
    else
        return false;
}

bool goodPair(char deschis, char inchis)
{
    if (deschis == '(' && inchis == ')')
        return true;
    else if (deschis == '[' && inchis == ']')
        return true;
    else if (deschis == '{' && inchis == '}')
        return true;
    else if (deschis == '<' && inchis == '>')
        return true;
    else
        return false;
}

bool check(std::string s)
{
    Element* S;
    for (int i = 0; i < s.length(); i++)
    {
        if (s[i] == '(' || s[i] == '[' || s[i] == '{' || s[i] == '<')
            push(S, s[i]);
        else
        {
            if (s[i] == ')' || s[i] == ']' || s[i] == '}' || s[i] == '>')
                if (isEmpty(S) || !goodPair(top(S), s[i]))
                    return false;
                else
                    pop(S);
        }
    }
    if (isEmpty(S))
        return false;
    else
        return true;

}

主文件

#include <iostream>
#include <string>
#include "header.h"
using namespace std;

int main()
{
    Stack S;
    initStack(S);
    string s;
    cout << "Write the string:";
    cin >> s;
    if (check(s))
        cout << "Good";
    else
        cout << "Bad";
    return 0;

}

我使用了一个栈,我遍历了每个字符。如果字符是左括号我把它放入栈中。当字符是右括号时,我将它与栈顶进行比较。如果好我弹出栈顶。

【问题讨论】:

  • 不是问题,但这很糟糕:typedef Element* Stack;,因为它在声明中隐藏了*,并在您的代码中造成了一些意外,例如Stack aux ... delete aux;

标签: c++ data-structures stack


【解决方案1】:

您在main() 中创建一个指向Element(别名为StackS 的指针,并使用initStack() 将其初始化为nullptr,然后您不再使用此变量。相反,您在函数 check() 中创建一个本地 S 并未初始化使用它,这会导致 UB。

看起来你对命名时感到困惑Smain() 中的变量,check() 中的变量,所有引用参数都称为S)。这样做并不违法,但看起来你自己搞糊涂了。 (你甚至叫std::string小写s来增加混乱)

你的函数也有逻辑错误:

if (isEmpty(S))
    return false;
else
    return true;

应该相反,如果堆栈为空,则字符串是平衡的,反之亦然。所以替换为:

return isEmpty( S );

【讨论】:

    猜你喜欢
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多