Queues are often implemented using chained storage. To facilitate operations, we need to maintain a header pointer and a tail pointer, just like sequential storage. For example:
It is clear that false overflow will not occur in the chain queue. However, when leaving the queue, the memory should be released in time. The queue implementation: the queue description is clear. If you don't have to talk about it, go directly to the Code:
Class definition and implementation
# Include
# Include
Using namespace std; typedef int ELemType; class QNode // node type {public: ELemType data; QNode * next; QNode (ELemType v, QNode * p = NULL ): data (v), next (p) {};}; class LinkQueue // chain queue {private: int size; QNode * front; // header pointer QNode * rear; // tail pointer public: LinkQueue (); // default constructor ~ LinkQueue (); // destructor int getSize (); // linked list size bool getFront (ELemType &); // get the head node bool getRear (ELemType &); // obtain bool empty (); // whether the queue is empty void clear (); // clear the linked table void enQueue (ELemType); // enter the void deQueue (); // void queueTraverse (); // queue traversal}; // class implementation LinkQueue: LinkQueue () {front = rear = NULL; size = 0;} LinkQueue ::~ LinkQueue () {clear ();} int LinkQueue: getSize () {return size;} bool LinkQueue: getFront (ELemType & item) {if (front) {item = front-> data; return true;} cout <"Empty queue! "<
Data; return true;} cout <"Empty queue! "<
Next; delete p; p = q ;}} rear = NULL; // You cannot forget size = 0;} void LinkQueue: enQueue (ELemType data) {if (front) {rear-> next = new QNode (data, NULL); rear = rear-> next;} else {front = rear = new QNode (data, NULL);} size ++;} void LinkQueue: deQueue () {if (front) {QNode * p = front; front = front-> next; delete p; size -- ;}} void LinkQueue: queueTraverse () {if (front) {QNode * p = front; while (p) {cout <
Data; p = p-> next;} cout <
Main Function
Int main () {cout <"chained queue demonstration" <
> Item & item) queue. enQueue (item); cout <"traversal" <
Run:
Download: queue implementation: chained queue