字符串变成链表后,检查括号平衡。

3

作为一项任务,我需要从用户那里获取一个字符串,然后将其转换为列表,接着检查括号平衡性。但是,我一直得到警告:`warning: control reaches end of non-void function [-Wreturn-type]`。

#include<iostream>
#include<string>
#include<stacks>
class Node{
public:
char data;
Node *head;
Node *tail;
Node *next;
Node *node;

void addToList(char);
bool CheckList();
void StringToList(string, Node*);
};
Node* addToList(char data)
    {
        Node* newNode = new Node;
        newNode->data = data;
        newNode->next = NULL;
        return newNode;
};

Node* StringToList(string text, Node* head)
{
    head = addToList(text[0]);
    Node *CurrentNode = head;
    for (int i = 1; i <text.size(); i++){
        CurrentNode->next = addToList(text[i]);
        CurrentNode = CurrentNode->next;
    }
    return head;
}
bool CheckList(Node* head)
{
    char c;

    stack <char> p;
    int i = 0;
    Node* CurrentNode = head;
    while(CurrentNode != NULL){

        if('(' || '{' || '['== CurrentNode->data){
            p.push(CurrentNode->data);

                 if(')' == CurrentNode->data){
                c= p.top();
                p.pop();
                if (c == '{' || c == '['){
                    return false;

            }
        }
            else if('}' == CurrentNode->data){
                c= p.top();
                p.pop();
                if (c == '(' || c == '['){
                    return false;

            }
        }
            else if('}' == CurrentNode->data){
                c= p.top();
                p.pop();
                if (c == '(' || c == '['){
                    return false;

                }
        }



            }
    }
    CurrentNode = CurrentNode->next;


}

int main()
{
    string text = "(check)[";
    Node *head = NULL;

    head = StringToList(text, head);
    if(CheckList(head)){
        cout<<"MAMA MIA IT WORKED-A!";
    }
    else
        cout<<"IT'S-A STILL WORKING!!!";

    return 0;

}

任何帮助都将不胜感激。再次感谢您的时间。另外,如果我的代码看起来有点凌乱,请见谅,因为我对堆栈和列表还比较陌生。

警告非常擅长指出需要修复问题代码的行号。在gcc/clang上始终使用-Wall -Wextra -pedantic进行编译,或者在VS(cl.exe)上使用/W3,并且在没有警告的情况下不接受代码。还可以考虑添加-Wshadow以识别可能有问题的变量和被遮蔽的变量。您可以从编译器中学到很多东西(尽管STL警告信息有点多...)。 - David C. Rankin
2个回答

3

CheckList声称返回一个bool,但是在 while 循环之后:

CurrentNode = CurrentNode->next;

你没有任何一个return语句。函数在不返回值的情况下就结束了。如果调用带有非void返回类型的函数结束时没有return语句(或通过异常提前退出),则程序的行为是未定义的。编译器正在警告您可能会发生这种情况。
你需要在函数末尾添加一个return语句,并带上你想要返回的值。鉴于函数中其他的return语句都返回了false,我认为你意图在整个循环执行完毕后返回true
CurrentNode = CurrentNode->next;
return true;

3
您的函数:
bool CheckList(Node* head)

代码末尾没有 return

    }
    CurrentNode = CurrentNode->next;


}

你必须返回一些东西:

    }
    CurrentNode = CurrentNode->next;

    return /* an appropriate boolean value */;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接