c++ - 我的字符串队列结构有什么问题?
问题描述
我无法让它正常工作,我正在尝试为一个字符串队列创建一个头文件,该文件具有 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 行之前的意外标记
解决方案
- 确保您使用
#include <string>
. - 而不是
string data;
,使用std::string data;
. 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 "";
}
推荐阅读
- jenkins - 来自 jenkins 的警告下一代插件 6.1.1 中使用了哪个版本的 Checkstyle?
- python - 根据另一列的值有条件地将渐变颜色应用于数据框单元格?
- mysql - 错误 1227 (42000):访问被拒绝;您需要(至少一个)在 SQL Workbench 中执行此操作的 SUPER 权限
- android - Android以编程方式更改可绘制纯色
- c# - 如何在文件C#中显示所有出现的特定单词
- css - Chrome,如何从 chrome Dev Tools 获取元素 css 样式 url()
- bash - 通过 ssh 使用 argjson 发送 jq
- java - NavigationView 不会自动隐藏
- c# - 带有 rtf 字符串源的 RichTextBox 显示不正确
- python - 如何将解码的数据矩阵写入数据帧