Write this as a struct and a class in C++.
struct node { data-type value; node* next; node(data-type value, node* next = nullptr) { this->value = value; this->next = next; } };
Data members
q_front
- pointer to front (first) node in the list.q_back
- pointer to back (last) node in the list.q_size
- Number of items currently stored in queue.Member Functions
Default constructor
Sets queue to initial empty state. The queue front pointer and the queue back pointer should be set to nullptr
. The queue size should be set to 0.
size()
Returns the queue size.
empty()
Returns true if the queue size is 0; otherwise, false.
clear()
We can easily set the queue back to the empty state by repeatedly calling pop()
until the queue is empty.
front()
Returns the front item of the queue (q_front->value
).
back()
Returns the front item of the queue (q_back->value
).
push()
Inserts a new item at rear of queue.
procedure push(value: item to insert) Allocate a new stack node, new_node new_node->value ← value if queue is empty q_front ← new_node else q_back->next = new_node end if q_back ← new_node q_size ← q_size + 1 end procedure
pop()
Removes the front item from queue.
procedure pop() delete_node ← q_front q_front ← q_front->next if q_front == nullptr q_back ← nullptr Delete the node delete_node q_size ← q_size - 1 end procedure
Copy Constructor
procedure queue(x : reference to a constant queue) // Set the new queue object's list to empty q_front ← q_back ← nullptr q_size ← 0 // Copy the other queue's linked list clone(x) end procedure
Copy Assignment Operator
procedure operator=(x : reference to a constant queue) if this != &x // Make the left queue object empty clear() // Copy the other queue's linked list clone(x) end if return *this; end procedure
Destructor
We can delete all of the dynamic storage for the stack by calling the clear()
member function.
clone()
Copies the linked list from the queue x
to this
object.
procedure clone(x : reference to a constant queue) ptr ← x.q_front while ptr != nullptr push(ptr->value) ptr ← ptr->next end while end procedure