#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
typedef int QElemType;
typedef int Status;
typedef struct QNode{
QElemType data;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear; //设置头尾指针
}LinkQueue;
Status InitQueue(LinkQueue &Q);
//创建一个空队列
Status DestoryQueue(LinkQueue &Q);
//销毁队列Q,Q不再存在
Status ClearQueue(LinkQueue &Q);
//将Q清为空队列
Status QueueEmpty(LinkQueue Q);
//若队列Q为空队列,则返回true,否则返回false
Status QueueLength(LinkQueue Q);
//返回Q的元素个数,即为队列的长度
Status GetHead(LinkQueue Q,QElemType &e);
//若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR
Status EnQueue(LinkQueue &Q,QElemType &e);
//插入元素e为Q的新的队尾元素
Status DeQueue(LinkQueue &Q,QElemType &e);
//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK否则返回ERROR
Status InitQueue(LinkQueue &Q){
Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
if(!Q.front) return ERROR;
Q.front->next=NULL;
return OK;
}
Status DestroyQueue(LinkQueue &Q){
while(Q.front){
Q.rear=Q.front->next;
free(Q.front);
Q.front=Q.rear;
}
return OK;
}
Status EnQueue(LinkQueue &Q,QElemType &e){
QNode* p=(QueuePtr)malloc(sizeof(QNode));
if(!p) return ERROR;
p->data=e; p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return OK;
}
Status DeQueue(LinkQueue &Q,QElemType &e){
if(Q.front==Q.rear) return ERROR;
QNode* p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p) Q.rear=Q.front;
free(p);
return OK;
}
Status GetHead(LinkQueue Q){
if(Q.front!=Q.rear)
return Q.front->next->data;
}
//Status GetHead(LinkQueue Q,QElemType &e){
// QueuePtr p;
// if(Q.front==Q.rear) return ERROR;
// p=Q.front->next;
// *e=p->data;
// return OK;
//}
Status ClearQueue(LinkQueue &Q){
QueuePtr p,q;
Q.rear=Q.front;
p=Q.front->next;
Q.front->next=NULL;
while(p){
q=p;
p=p->next;
free(q);
}
return OK;
}
Status QueueEmpty(LinkQueue Q){
if(Q.front==Q.rear)
return OK;
else
return ERROR;
}
Status QueueLength(LinkQueue Q){
int i=0;
QueuePtr p;
p=Q.front;
while(Q.rear!=p){
i++;
p=p->next;
}
return i;
}
Status visit(QElemType c){
printf("%d ",c);
return OK;
}
Status QueueTraverse(LinkQueue Q){
QueuePtr p;
p=Q.front->next;
while(p){
visit(p->data);
p=p->next;
}
printf("\n");
return OK;
}
int main(){
int i;
LinkQueue Q;
InitQueue(Q);
printf("是否为空队列%d(1:空 0:非空)\n",QueueEmpty(Q));
printf("队列的长度为%d\n",QueueLength(Q));
printf("请输入要入队的个数:");
int n; int e;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&e);
EnQueue(Q,e);
}
printf("队列的长度为%d\n",QueueLength(Q));
printf("队头元素为:%d\n",GetHead(Q));
printf("删除队头元素!!!\n");
DeQueue(Q,e);
printf("新的队头元素为:%d\n",GetHead(Q));
printf("新的队列为:");
QueueTraverse(Q);
ClearQueue(Q);
DestroyQueue(Q);
return 0;
}
队列的链式存储
最新推荐文章于 2024-08-10 20:38:44 发布