Question:
struct QueueNode {
int data;
QueueNode *next;
};
do
This is my code
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;
}
};
The Online Judge displayed wrong answer. I think the "int top() const" is wrong. But I have no idea. Ask for help. Thanks.
As @Kaylum pointed out, you have not returned the size of the queue if it is empty. It should return 0 in that case, but you have no else part in your size()
method.
This should probably work:
int size() const {
if (! is_empty())
return _size;
else
return 0;
}
EDIT: Similarly you should return something from top()
too. If you're using an online judge, then it would have specified what to return in case of empty queues. Read the constraints again please, I guess it would help. It would most probably some exception or some default integer which would be required by the online judge to judge an empty queue's output.
My answer. Thanks Everyone.
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;
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.