- #include<iostream.h>
- //#include<stdlib.h>
- template<class T>
- struct linknode
- {
- T data;
- linknode<T> *link;
- linknode<T>(linknode<T> *ptr=NULL)
- {
- link=ptr;
- }
- linknode<T>(const T&item,linknode<T> *ptr=NULL)
- {
- link=ptr;
- data=item;
- }
- };
- template<class T>
- class linkedqueue
- {
- public:
- linkedqueue():rear(NULL),front(NULL)
- {
- }
- ~linkedqueue()
- {
- makeempty();
- }
- bool enqueue(const T&x);
- bool dequeue(T&x);
- bool getfront(T&x)const;
- void makeempty();
- bool isempty()const
- {
- return (front==NULL)?true:false;
- }
- int getsize()const;
- void show()const;
- //friend ostream& operator<<(ostream& os,linkedqueue<T>& Q);
- protected:
- linknode<T> *front,*rear;
- };
- template<class T>
- void linkedqueue<T>::makeempty()
- {
- linknode<T> *p;
- while(front!=NULL)
- {
- p=front;
- front=front->link;
- delete p;
- }
- };
- template<class T>
- bool linkedqueue<T>::enqueue(const T&x)
- {
- int s;
- cout<<"请选择插入数据的端:1 队头 2 队尾 :";
- cin>>s;
- if(s==2)
- {
- if(front==NULL)
- {
- front=rear=new linknode<T>(x);
- if(front==NULL)
- return false;
- }
- else
- {
- rear->link=new linknode<T>(x);
- if(rear->link==NULL)
- return false;
- rear=rear->link;
- }
- return true;
- }
- else if(s==1)
- {
- if(front==NULL)
- {
- front=rear=new linknode<T>(x);
- if(front==NULL)
- return false;
- }
- else
- {
- linknode<T> *p;
- p=front;
- front=new linknode<T>(x);
- front->link=p;
- }
- return true;
- }
- };
- template<class T>
- bool linkedqueue<T>::dequeue(T&x)
- {
- if(isempty()==true)
- return false;
- linknode<T> *p=front;
- x=front->data;
- front=front->link;
- delete p;
- return true;
- };
- template<class T>
- bool linkedqueue<T>::getfront(T&x)const
- {
- if(isempty()==true)
- return false;
- x=front->data;
- return true;
- };
- template<class T>
- int linkedqueue<T>::getsize()const
- {
- linknode<T>*p;
- p=front;
- int k=0;
- while(p!=NULL)
- {
- p=p->link;
- k++;
- }
- return k;
- };
- template<class T>
- void linkedqueue<T>::show()const
- {
- linknode<T>* p=front;
- while(p!=NULL)
- {
- cout<<p->data<<" ";
- p=p->link;
- }
- cout<<endl;
- };
- void main()
- {
- linkedqueue<int> myqueue;
- for(int i=1;i<=3;i++)
- {
- myqueue.enqueue(i);
- }
- myqueue.show();
- for(i=1;i<=3;i++)
- {
- myqueue.enqueue(i);
- }
- myqueue.show();
- // int x;
- // myqueue.dequeue(x);
- // cout<<x<<endl;
- // myqueue.show();
- // cout<<myqueue.getsize()<<endl;
- }
- //该片段来自于http://www.codesnippet.cn/detail/141020136392.html
来源: http://www.codesnippet.cn/detail/141020136392.html