循环队列数组实现

循环队列的数组实现:

queue.h
 
   
#ifndef QUEUE_H
#define QUEUE_H

typedef
int ElementType;

struct QueueRecord;
typedef
struct QueueRecord * Queue;

int IsEmpty(Queue q);
int IsFull(Queue q);
Queue CreateQueue(
int maxElements);
void DisposeQueue(Queue q);
void MakeEmpty(Queue q);
int Enqueue(ElementType x, Queue q);
int Dequeue(Queue q);
ElementType Front(Queue q);
ElementType FrontAndDequeue(Queue q);

#endif
queue.c

queue.c
 
   
#include < stdio.h >
#include
< string .h >
#include
< stdlib.h >
#include
" queue.h "

#define SAFE_FREE(q) {if (q) {free(q); q = NULL;}}

struct QueueRecord
{
int capacity;
int front;
int rear;
int size;
ElementType
* array;
};

int IsEmpty(Queue q)
{
return q -> size == 0 ;
}

int IsFull(Queue q)
{
return q -> size == q -> capacity;
}

Queue CreateQueue(
int maxElements)
{
Queue q
= malloc( sizeof ( struct QueueRecord));
if (q == NULL)
{
fprintf(stderr,
" create queue failed. " );
return NULL;
}
q
-> array = malloc(maxElements * sizeof ( char ));
if (q -> array == NULL)
{
fprintf(stderr,
" create queue failed. " );
return NULL;
}
q
-> capacity = maxElements;
q
-> front = q -> rear = 0 ;
q
-> size = 0 ;

return q;
}

void DisposeQueue(Queue q)
{
if (q == NULL)
{
fprintf(stderr,
" the queue is NULL. " );
return ;
}
SAFE_FREE(q
-> array);
SAFE_FREE(q);
}

void MakeEmpty(Queue q)
{
if (q == NULL)
{
fprintf(stderr,
" the queue is NULL. " );
return ;
}
q
-> front = q -> rear = 0 ;
q
-> size = 0 ;
memset(q
-> array, 0x00 , q -> capacity);
}

int Enqueue(ElementType x, Queue q)
{
if (IsFull(q))
{
fprintf(stderr,
" queue is full. " );
return - 1 ;
}
if (IsEmpty(q))
{
q
-> array[q -> front] = x;
}
else
{
if ((q -> rear + 1 ) == q -> capacity)
{
q
-> rear = 0 ;
q
-> array[q -> rear] = x;
}
else
{
q
-> array[ ++ q -> rear] = x;
}
}
q
-> size ++ ;
printf(
" size = %d\n " , q -> size);

return 0 ;
}

int Dequeue(Queue q)
{
if (IsEmpty(q))
{
fprintf(stderr,
" queue is empty. " );
return - 1 ;
}

q
-> array[q -> front] = 0 ;
if ((q -> front + 1 ) == q -> capacity)
{
q
-> front = 0 ;
}
else
{
q
-> front ++ ;
}
q
-> size -- ;
return 0 ;
}

ElementType Front(Queue q)
{
if (q == NULL)
{
fprintf(stderr,
" queue is empty. " );
return - 1 ;
}
return q -> array[q -> front];
}

 

转载于:https://www.cnblogs.com/python_newbie/archive/2010/10/23/1858972.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值