队列的链式存储结构,其实就是线性表的单链表,只不过它只能尾进头出。简称链队列。
实现代码如下:
/* LinkQueue.h 头文件 */ #include<iostream> #define OK 1 #define ERROR 0 typedef int QElemType; typedef int Status; class QNode{ public: QNode():data(0),next(NULL) {} QElemType data; QNode *next; }; class LinkQueue{ public: LinkQueue() {front=new QNode;rear=new QNode;front=rear;} Status EnQueue(QElemType e); /*入队操作*/ Status DeQueue(QElemType *e); /*出队操作*/ Status ShowQueue() const; private: QNode *front,*rear; /*队头、队尾指针,队头不保存元素,只起头结点作用,当front==rear时,队列为空*/ }; Status LinkQueue::EnQueue(QElemType e) { QNode *p=new QNode; if(!p) return ERROR; p->data=e; p->next=NULL; rear->next=p; rear=p; return OK; } Status LinkQueue::DeQueue(QElemType *e) { if(rear==front) /*空队列*/ return ERROR; QNode *p=new QNode; if(!p) return ERROR; p=front->next; *e=p->data; front->next=p->next; if(rear==p) rear=front; delete p; return OK; } Status LinkQueue::ShowQueue() const { if(rear==front) { std::cout<<"空队列"<<std::endl; return ERROR; } QNode *p=new QNode; if(!p) return ERROR; std::cout<<"队列从队头至队尾内容依次为:"; p=front->next; while(p) { std::cout<<p->data<<" "; p=p->next; } std::cout<<std::endl; return OK; }