【发布时间】:2021-06-26 06:07:18
【问题描述】:
问题:
struct QueueNode {
int data;
QueueNode *next;
};
做
- int size() const:返回数据大小。
- bool is_empty() 常量:
- void enqueue(int val):将新节点添加到列表末尾。
- void dequeue():移除head指向的节点。
- int top() const:返回下一个出队的数据。
这是我的代码
class Queue {
private:
QueueNode *_head = NULL, *_tail = NULL;
int _size = 0;
public:
int size() const {
if (! is_empty())
return _size;
}
bool is_empty() const {
if (_size == 0)
return true;
else
return false;
}
void enqueue(int val) {
QueueNode *n = new QueueNode;
n -> data = val;
n -> next = NULL;
if (is_empty()) {
_head = n;
_tail = n;
_size ++;
}
else {
_tail -> next = n;
_tail = n;
_size ++;
}
}
void dequeue() {
QueueNode *temp;
temp = _head;
if (! is_empty()) {
_head = _head -> next;
delete temp;
_size --;
}
}
int top() const {
if (! is_empty())
return _head -> data;
}
};
在线裁判显示错误答案。 我认为“int top() const”是错误的。 但我不知道。 请求帮忙。 谢谢。
【问题讨论】:
-
队列为空时
size()和top()返回什么? -
_head = _tail = n;应该写成单独的作业。如果队列为空,top()和size()不返回任何内容。 -
@kaylum 不需要返回,只有返回队列不为空
-
呃,方法不是这样工作的。如果您将其定义为返回某些内容,则它必须针对每种情况都这样做。否则结果是未定义的行为。
-
@dave
_head = n; _tail = n;没关系。
标签: c++ data-structures linked-list queue