- /*
- * queue.cpp
- *
- * Created on: 2012-5-13
- * Author: awind
- * 队列的链式表示
- */
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- typedef struct QNode{
- int data;
- struct QNode *next;
- }QNode,*QueuePtr;
- typedef struct{
- QueuePtr front; //队头指针
- QueuePtr rear; //队尾指针
- }LinkQueue;
- bool InitQueue(LinkQueue &Q) //创建一个空队列
- {
- Q.front=Q.rear=new QNode;
- if(!Q.front)
- return false;
- Q.front->next=NULL;
- return true;
- }
- bool DestroyQueue(LinkQueue &Q) //销毁队列
- {
- while(Q.front){
- Q.rear=Q.front->next;
- delete Q.front;
- Q.front=Q.rear;
- }
- return true;
- }
- bool EnQueue(LinkQueue &Q,int e) //插入元素为e的新的队尾元素
- {
- QNode *p=new QNode;
- if(!p)
- return false;
- p->data=e;
- p->next=NULL;
- Q.rear->next=p; //尾指针指向插入的元素
- Q.rear=p; //插入的元素成为尾指针
- return true;
- }
- bool DeQueue(LinkQueue &Q,int &e) //若队列不为空,则删除Q的队头元素
- {
- if(Q.front==Q.rear)
- return false;
- QNode *p=new QNode;
- p=Q.front->next;
- e=p->data;
- Q.front->next=p->next;
- if(Q.rear==p)
- Q.rear=Q.front;
- delete p;
- return true;
- }
- bool QueueEmpty(LinkQueue Q) //队列是否为空
- {
- return Q.front==Q.rear;
- }
- bool ClearQueue(LinkQueue &Q) //将队列清空
- {
- QNode *p=new QNode;
- p=Q.front->next;
- while(p)
- {
- Q.rear=p->next;
- delete p;
- p=Q.rear;
- }
- Q.rear=Q.front;
- Q.front->next=NULL;
- return true;
- }
- int QueueLength(LinkQueue Q) //返回队列的长度
- {
- int count=0;
- if(Q.front==Q.rear)
- return 0;
- QNode *p=new QNode;
- p=Q.front->next;
- while(p)
- {
- ++count;
- p=p->next;
- }
- return count;
- }
- bool GetHead(LinkQueue Q,int &e) //若队列不为空 则用e返回Q的队头元素
- {
- if(Q.front==Q.rear)
- return false;
- e=Q.front->next->data;
- return true;
- }
- bool QueueTraverse(LinkQueue Q)
- {
- if(Q.front==Q.rear)
- return false;
- QNode *p=new QNode;
- p=Q.front->next;
- while(p)
- {
- cout<<p->data<<" ";
- p=p->next;
- }
- return true;
- }
- int main()
- {
- LinkQueue Q;
- InitQueue(Q);
- cout<<"input the num of the Queue: ";
- int stackNum;
- cin>>stackNum;
- for(int i=0;i<stackNum;i++)
- {
- int elem;
- cout<<"input the element of the stack: ";
- cin>>elem;
- EnQueue(Q,elem);
- }
- QueueTraverse(Q);
- cout<<"\n";
- cout<<"the length of the Queue: "<<QueueLength(Q)<<endl;
- ClearQueue(Q);
- cout<<"input the num of the Queue: ";
- cin>>stackNum;
- for(int i=0;i<stackNum;i++)
- {
- int elem;
- cout<<"input the element of the stack: ";
- cin>>elem;
- EnQueue(Q,elem);
- }
- QueueTraverse(Q);
- cout<<"\n";
- cout<<"the length of the Queue: "<<QueueLength(Q)<<endl;
- }