1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
#include<iostream> #include<cstring> #include<cstdlib> #include<cassert> using namespace std;
template<typename T> class LinkQueue{
private: int size; struct Node{ T e; Node *next; Node(){ this->e=NULL; this->next=NULL; } Node(T e){ this->e=e; this->next=NULL; } Node(T e,Node *next){ this->e=e; this->next=next; } }; Node *tail,*front;
public: LinkQueue(){ this->size=0; this->tail=this->front=NULL; }
//得到队列中的元素个数 int getSize(){ return this->size; }
//判断队列是否为空 bool isEmpty(){ return size==0; }
//入队操作 void enqueue(T e){ if(tail==NULL){ tail=new Node(e); front=tail; } else { tail->next=new Node(e); tail=tail->next; } size++; }
//出队操作 T dequeue(){ assert(!isEmpty()); Node *retnode=front; front=front->next; retnode->next=NULL; if(front==NULL) tail=NULL; size--; return retnode->e; }
//打印队列中的元素 void PrintLinkQueue(){ assert(!isEmpty()); Node *head=front; cout<<"front "; while(head!=NULL){ cout<<head->e; if(head->next) cout<<"->"; head=head->next; } cout<<" tail"<<endl; } };
int main() {
LinkQueue <int>*arr=new LinkQueue<int>(); for(int i=1;i<6;i++){ arr->enqueue(i); } cout<<"队列为:"; arr->PrintLinkQueue();
cout<<"出队的元素为:"; cout<<arr->dequeue()<<endl; cout<<"队列为:"; arr->PrintLinkQueue();
return 0; }
|
近期评论