Question:
struct QueueNode {
int data;
QueueNode *next;
};
do
- int size() const: return data size.
- bool is_empty() const:
- void enqueue(int val): add a new node to the end of the list.
- void dequeue(): remove the node which head point to.
- int top() const: return the data which will be dequeue next.
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.
size()
andtop()
return when the queue is empty? – kaylum_head = _tail = n;
should be written as separate assignments.top()
andsize()
don't return anything if the queue is empty. – dave_head = n; _tail = n;
It's ok. – d901203