Queue
Simple implementation of the push pop empty size;
The same as the chain implementation of the stack, because the delete operation needs to hold the next element, so the queue delete operation pops to the list of the head implementation
Because the queue is first in first out, the insert operation push is inserted at the end of the list.
"Test Code"
#include <cstdio> #include <iostream> #include <malloc.h>using namespace std; #define MaxSize 100typedef int ElementType; ElementType ERROR = -1;struct qnode{ElementType Data; Qnode *next;}; Class Linkqueue{public:linkqueue () {//establishes a new node and points the head and tail pointers of the storage queue to the area qnode* q= (qnode*) malloc (sizeof (Qnode)); q->data=0; Q->next=null;rear=q;front=q;} bool Empty () {if (front = = rear) {///the queue is empty return true;} return false;} int size () {qnode* tmp=front;int sz=0;while (tmp!=rear) {//from "head" to "tail" length is the queue size tmp=tmp->next;sz++;} return sz;} void Push (ElementType X) {qnode* lastcell= (qnode*) malloc (sizeof (Qnode)); Lastcell->data = X; lastcell->next=null; Always let the end of next be empty Rear->next = lastcell;//The next assignment of the original team tail is the newly established node Rear=lastcell; Update Team tail}elementtype Pop () {Qnode *frontcell; ElementType frontelem;//The temporary node that was created to output the return value and the variable if (empty ()) {cout<< "Queue empty" <<endl; return ERROR;} Frontcell = Front; Front = front->next; The head node always does not save data, the data is on the next node of the head Frontelem = Frontcell->next->data;free (Frontcell); return FronteLem;} Private:qnode *rear; Point to the tail node of the queue Qnode *front; Point to the Team head node};int main () {Linkqueue Q; Q.push (4); Q.push (5); Q.push (5);cout<< "Size:" <<q.size () <<endl;cout<<q.pop () <<endl;cout<<q.pop () <<endl;cout<<q.pop () <<endl;cout<<q.pop () <<endl;cout<< "Size:" <<q.size ( ) <<endl;return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
A chain-store implementation of data structure learning---queue