I’ve introduced the Queue structure in previous post. In contiguous storage, queues were significantly harder to manipulate than were stacks, because it was necessary to treat straight-line storage as though it were arranged in a circle, and the extreme cases of full queues and empty queues caused difficulties. As a result, I introduce you the linked queue in this post.
Implementation
Based on the previous definition of Queue, I’ll give the definition of LinkedQueue.(LinkedQueue.hpp)
preposition: None. postposition: Add item to the rear of the Queue and return a code of Success or return a code of OverFlow if dynamic memory is exhausted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
template <classQueue_entry> Error_code LinkedQueue<Queue_entry>::append(const Queue_entry &item) { Node<Queue_entry>* new_rear = new Node<Queue_entry>(item); //System's memory is exhausted if (new_rear == NULL) { return OverFlow; } if (rear == NULL) { front = rear = new_rear; } else { rear->next = new_rear; rear = new_rear; } return Success; }
serve()
preposition: None. postposition: The front of the Queue is removed. If the Queue is empty, return an Error_code of UnderFlow.
preposition: None. postposition:If the Queue is not empty, the front of the Queue has been recorded as item, and return Success. Otherwise an Error_code of UnderFlow is returned.
preposition: None. postposition: Return the number of entries in the Queue.
1 2 3 4 5 6 7 8 9 10
template <classQueue_entry> int LinkedQueue<Queue_entry>::size() const { int size = 0; Node<Queue_entry> *p1 = this->front; while (p1 != NULL) { p1 = p1->next; size++; } return size; }
serve_and_retrieve(Queue_entry &item)
preposition: None. postposition: Return UnderFlow if the Queue is empty. Otherwise remove and copy the item at the front of the Queue to item and return Success.
Hereto, I’ve show you the Queue by using linked storage. This dynamic way to store elements enables us to handle data more conveviently and handy. Hope this post will be helpful to you. Thank you so much!