链队列
#include<iostream.h> #include<stdlib.h> #define OK 1 #define OVERFLOW -2 #define ERROR 0 typedef int Status; typedef int QElemType; typedef struct QNode { //结点类型 QElemType data; struct QNode *next; }QNode,*QueuePtr; typedef struct { //链队列类型 QueuePtr front; //队头指针 QueuePtr rear; //队尾指针 }LinkQueue; Status InitQueue(LinkQueue &Q) { //构造一个空队列Q Q.front=Q.rear=new QNode; if(!Q.front) exit(OVERFLOW); //存储分配失效 Q.front->next=NULL; return OK; } int QueueEmpty(LinkQueue &Q) { return Q.front==NULL; } //取队头元素 int GetFront(LinkQueue &Q,QElemType &x) { QNode *p; if(QueueEmpty(Q)) return 0; p=Q.front->next; x=p->data; } Status EnQueue(LinkQueue &Q,QElemType e) { //插入元素e为Q的新的队尾元素 QNode *p; p=new QNode; if(!p) exit(OVERFLOW); //存储分配失效 p->data=e; p->next=NULL; Q.rear->next=p; Q.rear=p; return OK; } Status DeQueue(LinkQueue &Q,QElemType &e) { //若队列不空,则删除Q的队头元素, //用e返回其值,并返回OK; 否则返回ERROR QNode *p; if(Q.front==Q.rear) return ERROR; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear==p) Q.rear=Q.front; delete p; return OK; } void CreateQueue(LinkQueue &Q,int n) { QElemType e; cout<<"input n(e)="; for(int i=1;i<=n;i++) { cin>>e; EnQueue(Q,e); } } void VisitQueue(LinkQueue Q) { QNode *p=Q.front->next; while(p) { cout<<p->data<<" "; p=p->next; } cout<<endl; } void main() { LinkQueue Q; int n; QElemType x; InitQueue(Q); cout<<"input n="; cin>>n; CreateQueue(Q,n); VisitQueue(Q); if(GetFront(Q,x)) cout<<x<<endl; cout<<"input x="; cin>>x; if(EnQueue(Q,x)) VisitQueue(Q); cout<<"DeQueue\n"; if(DeQueue(Q,x)) VisitQueue(Q); else cout<<"Queue is Empty\n"; }