您的位置:首页 > 其它

队列的数组实现

2015-09-23 14:09 375 查看
声明 curosr_queue.h:

#ifndef CURSOR_QUEUE_H_INCLUDED
#define CURSOR_QUEUE_H_INCLUDED
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);
void Enqueue(int X, Queue Q);
int Front(Queue Q);
int Dequeue(Queue Q);
int FrontAndDequeue(Queue Q);

#endif // CURSOR_QUEUE_H_INCLUDED


实现 implementation.c:

#include<stdio.h>
#include "cursor_queue.h"

#define MinQueueSize 5

struct QueueRecord{
int Capacity;
int Front;
int Rear;
int Size;
int *Array;
};

int IsEmpty(Queue Q){
return Q->Size == 0;
}

Queue CreateQueue(int MaxElements) {
Queue Q;
if(MaxElements < MinQueueSize)
printf("Too small queue size!");
Q = malloc(sizeof(struct QueueRecord));
if(Q == NULL) {
printf("Out of space!");
}
Q->Array = malloc(sizeof(int) * MaxElements);
if(Q->Array == NULL){
printf("Out of space!");
}
MakeEmpty(Q);
Q->Capacity = MaxElements;
return Q;
}

void MakeEmpty(Queue Q) {
Q->Rear = 0;
Q->Front = 1;
Q->Size = 0;
}

static int Succ(int Value, Queue Q) {
if(++Value == Q->Capacity)
Value = 0;
return Value;
}

int IsFull(Queue Q) {
return Q->Size == Q->Capacity;
}

void Enqueue(int X, Queue Q) {
if(IsFull(Q))
printf("Error! Full Queue!\n");
else{
Q->Size++;
Q->Rear = Succ(Q->Rear, Q);
Q->Array[Q->Rear] = X;
}
}

int Dequeue(Queue Q){
int Data;
if(IsEmpty(Q)){
printf("Error, empty queue!");
return -1;
}
else{
Q->Size--;
Data = Q->Array[Q->Front];
Q->Front = Succ(Q->Front, Q);
}
return Data;
}

void DisposeQueue(Queue Q) {
free(Q->Array);
free(Q);
}


测试 main.c:

#include <stdio.h>
#include <stdlib.h>
#include "cursor_queue.h"

int main()
{
Queue Q;
Q = CreateQueue(10);
int i = 0;
for(i = 0; i < 10; i++)
Enqueue(i ,Q);
Enqueue(10, Q);
for(i = 0; i < 10; i++)
printf("%d ", Dequeue(Q));
printf("\n");
DisposeQueue(Q);
Q = CreateQueue(10);
for(i = 0; i < 10; i++)
printf("%d\n", Dequeue(Q));
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: