您的位置:首页 > 理论基础 > 数据结构算法

数据结构队列的各种操作

2012-03-26 21:45 295 查看
#include"stdio.h"
#include"stdlib.h"
typedef int ElementType;
typedef struct Queue
{
int rear,front;
ElementType *elements;
int MaxSize;
}Queue;
void InitQueue(Queue *Q,int sz)//初始化
{
Q->MaxSize=sz;
Q->elements=(ElementType *)malloc(sizeof(ElementType)*Q->MaxSize);
Q->front=Q->rear=0;
}
void freeQueue(Queue *Q,int sz)//释放空间
{
free(Q->elements);
}
void MakeEmpty(Queue *Q)//置空
{
Q->front=Q->rear=0;
}
int Length(Queue *Q)//返回长度
{
return (Q->rear-Q->front+Q->MaxSize)%(Q->MaxSize);
}
int IsFull(Queue *Q)//判断是否为满
{
if (Q->rear!=0&&(Q->front==(Q->rear)%(Q->MaxSize)))
return 1;
else
return 0;
}
int IsEmpty(Queue *Q)//判断是否为空
{
if(Q->front==Q->rear)
return 1;
else
return 0;
}
void EnQueue(Queue *Q)//进队
{   ElementType item;
scanf("%d",&item);
while((!IsFull(Q))&&(item!=-1))
{
Q->elements[Q->rear]=item;
Q->rear=(Q->rear+1)%(Q->MaxSize);
scanf("%d",&item);
}
}
ElementType DeQueue(Queue *Q)
{
ElementType item;
if(!IsEmpty(Q))
{
item=Q->elements[Q->front];
Q->front=(Q->front+1)%(Q->MaxSize);
return item;
}
else
{
printf("对空!\n");
exit(1);
}
}
ElementType GetFront(Queue *Q)
{
if(!IsEmpty(Q))
return Q->elements[Q->front];
else
{
printf("队空!\n");
exit(1);
}
}
void main()
{
int i;
Queue Q;
InitQueue(&Q,10);
EnQueue(&Q);
for(i=0;i<10;i++)
if(!IsEmpty(&Q))
printf("%-5d",DeQueue(&Q));
}


本文出自 “优赛工作室” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/817866
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: