Let us recall the Node class from last time.
// define our Node class
class Node{
private:
int data;
Node* next;
public:
// default constructor, set things to zero and null
Node(){
data = 0;
next = nullPtr;
}
// a constructor that only recieves the integer part
Node(int d){
data = d;
next = nullPtr;
}
// a constructor that recieves both parts
Node(int d, Node* n){
data = d;
next = n;
}
// let's implement a destructor
~Node(){
delete next;
}
// data getter
int getData(){
return data;
}
// next getter (to get the pointer to the next node)
Node* getNext(){
return next;
}
// set data
void setData(int d){
data = d;
}
// set next node
void setNext(Node* n){
next = n;
}
}
enqueue() → adds a new element at the tail of the queuedequeue() → retrieves the element at the head of the queueclass Queue(){
private:
// the pointer to the head and tail
Node* head;
Node* tail;
public:
// constructor
Node(){
head = nullptr;
tail = nullptr;
}
// destructor
~Node(){
// the delete Node function will recursively delete everything (even tail)
delete head;
}
// enque function
void enqueue(){
Node* p = new Node(3);
// check if head (and therefore tail) are null (empty queue)
if (head == nullptr){
head = p;
tail = p;
}
else{
tail->setNext(p);
tail = p;
}
}
// deque function
int dequeue(){
// if our queue is empty
if (head == nullptr)
return -1;
// secure our head
Node* p = head;
// readjust head
head = head->getNext();
// secure integer we want to return
int data = p->getData();
// we sever the link
p->setNext(nullptr);
// delete p and return data
delete p;
// make sure if the head == null after this (we have emptied our queue)
// we don't want to keep tail dangling, so we put tail to null.
if (head == nullptr)
tail = nullptr;
return data;
}
}
What happens when we enqueue(3)?
NULL.next of the tail points to our new node.tail pointer to point to our new node.What happens if queue empty?
NULL and tail is NULLtail is not pointing to any Node objectif statement to check if the queue is empty