队列的数组实现

来源:互联网 发布:nginx etag 配置 编辑:程序博客网 时间:2024/05/21 09:45

摘要:(1)QueeRecord,队列的基本结构,queue指向它的指针
(2)初始化的时候,Front = 1,rear = 0;注意,为什么队列没有元素的时候队尾队首要不同呢?因为队列只有一个元素是队尾队列才一样,因此出队一个元素,队首Front加1,从而得到该结果.
(3)为了便于理解,可以将队列理解为一个初始时队首面向数组第一个元素,进队时队尾增加,因此Rear++,队列变长。出队时队首Front++,队列变短。(第一个人转移到他右边一个)
(4)为了保证队列的空满不出错,用一个变量(size)和容量capcity比较来判断.
(5)为了充分利用该队列的空间,避免造成进队出队次数太多,而队尾越界的情况。采取循环队列的结构(就是对变量Front,rear取余).

#include "stdafx.h"#include "malloc.h"typedef struct QueueRecord *queue;struct QueueRecord{int capacity;int size;int Front;int Rear;int *Array;};queue Create(int MaxElements){    queueQ = (queue)malloc(sizeof(QueueRecord));Q->Array = (int *)malloc(sizeof(int)*MaxElements);Q->capacity = MaxElements;Q->size = 0;Q->Front = 1;Q->Rear = 0;return Q;}void Enqueue(queue Q,int x){//循环队列if (Q->size == Q->capacity)puts("cannot Enqueue for the full queue");else{Q->Array[(++Q->Rear)%(Q->capacity)] = x;    Q->size++;}return;}int Dequeue(queue Q){if (Q->size == 0){puts("cannot Dequeque for an empty queue");        return (-1);}else{Q->size--;return Q->Array[Q->Front++];}}int _tmain(int argc, _TCHAR* argv[]){int i = 0;queue Q;Q = Create(10);while(i++ <= 5 )Enqueue(Q,i);while(i--> 1)printf("%d " ,Dequeue(Q));return 0;}
0 0
原创粉丝点击