首页 > 解决方案 > 我的字符串队列结构有什么问题?

问题描述

我无法让它正常工作,我正在尝试为一个字符串队列创建一个头文件,该文件具有 pop 函数,它返回并删除队列中的第一个值,push 将一个值插入到末尾, isEmpty 检查队列是否为空。

#ifndef Queue_h
#define Queue_h
#include <string>

struct Node {
    string data;
    Node* next;

    Node() {
        data = "";
        next = NULL;
    }

};

struct Queue {
    Node* first;
    Node* last;

    Queue() {
        first = NULL;
        last = NULL;
    }

    ~Queue() {
        Node* temp = first;

        while (temp != NULL) {
            temp = temp->next;
            delete first;
            first = temp;
        }
    }
    void push(string input) {
        if (isEmpty()) {
            Node* node = new Node();
            first = node;
            last = node;
            last->data = input;
        }
        else {
            Node* node2 = new Node();
            last->next = node2;
            last = last->next;
            last->data = input;
        }
    }

    string pop() {
        if (!isEmpty()) {
            string temp = first->data;
            Node* tpointer = first;
            first = first->next;
            delete tpointer;
            return temp;
        }
        return "";
    }

    bool isEmpty() {
        if (first == NULL) {
            return true;
        }
        else {
            return false;
        }
    }
};

#endif

我收到一堆错误,比如“数据不是节点的成员”“数据是未声明的标识符”“数据是未知的覆盖说明符”。我会复制/粘贴我的错误列表,但我不知道如何轻松做到这一点。

编辑:现在我在修复我的字符串声明后减少了 4 个错误:pop 不是队列第 17 行的成员,pop 未知覆盖说明符第 50 行,语法错误(第 50 行,{第 50 行之前的意外标记

标签: c++structqueue

解决方案


  1. 确保您使用#include <string>.
  2. 而不是string data;,使用std::string data;.
  3. std::string也可以string在所有其他地方使用。

我最初将上面的前两项作为评论发布,但我注意到pop()函数中有一个错误。我想我也会将它们添加到这个答案中。

last从 . 弹出最后一项时,您没有正确更新Queue

std::string pop() {
    if (!isEmpty()) {
        std::string temp = first->data;
        Node* tpointer = first;
        if ( first == last )
        {
           first = last = NULL;
        }
        else
        {
           first = first->next;
        }
        delete tpointer;
        return temp;
    }
    return "";
}

推荐阅读