[英]C++ Queue with Linked-list
問題:
struct QueueNode {
int data;
QueueNode *next;
};
做
這是我的代碼
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”是錯誤的。 但我不知道。 請求幫忙。 謝謝。
正如@Kaylum 指出的那樣,如果隊列為空,您還沒有返回隊列的大小。 在這種情況下它應該返回 0,但你的size()
方法中沒有其他部分。
這應該可以工作:
int size() const {
if (! is_empty())
return _size;
else
return 0;
}
編輯:同樣你也應該從top()
返回一些東西。 如果您使用在線法官,那么它會指定在空隊列的情況下返回什么。 請再次閱讀約束,我想這會有所幫助。 這很可能是一些異常或一些默認的 integer,在線法官需要這些異常來判斷一個空隊列的 output。
我的答案。 感謝大家。
class Queue {
private:
QueueNode *_head = NULL, *_tail = NULL;
int _size = 0;
public:
int size() const {
if (! is_empty())
return _size;
else
return 0;
}
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 = _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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.