队列的链式存储

#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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值