用数组实现队列--静态队列

来源:互联网 发布:常用的mysql语句 编辑:程序博客网 时间:2024/06/05 15:23
/*  一、关于静态队列的约定(目的是在C语言中描述方便)  1.定义:和栈相反,队列是一种先进先出的线性表,它只允许在表的一端进行插入,在另一端进行删除元素。在队列中,允许插入的一端叫队尾,允许删除的一端较队头,即入队只能从队尾入,出队只能从队头出。    2.初始化建空队列时,令front=rear=0;入队时,队尾指针rear增1;出队时队头指针增1。在非空队列中,队头指针front始终指向队列头元素,而队尾指针rear始终指向队列尾元素的下一个位置。    3.在C语言中不能使用动态分配的一维数组来实现循环队列。如果用户程序中有循环队列,则必须为它设定一个最大队列长度,若用户无法预估所用队列最大长度,则宜采用链队列。*/#include "ArrayQueue.h"void arrayQueueCreat(struct arrayQueue * qQ,int lengh){qQ->pBase =(int *)malloc(sizeof(int)*lengh);if( NULL == qQ->pBase ){printf("arrayQueueCreat(): malloc failed!\n");exit(-1);} qQ->arrayLen = lengh;qQ->queueLen = 0;qQ->front = 0;qQ->rear = 0;}int arrayQueueIsFull(struct arrayQueue * qQ){if( qQ->front == (qQ->rear+1)%(qQ->arrayLen) )    return 1;else    return 0;}int arrayQueueIsEmpty(struct arrayQueue * qQ){if( qQ->front == qQ->rear )    return 1;else    return 0;}//入队int enArrayQueue(struct arrayQueue * qQ,int val){if( 1 == arrayQueueIsFull(qQ) ){    printf("the array queue is full\n");    return 0;}qQ->pBase[qQ->rear] = val;//在队尾入qQ->rear = (qQ->rear+1)%(qQ->arrayLen);qQ->queueLen++;return 1;}//出队int outArrayQueue(struct arrayQueue * qQ,int * pVal){if( 1 == arrayQueueIsEmpty(qQ) ){     printf("the array queue is empty\n");    return 0;}*pVal = qQ->pBase[qQ->front];//在队头出qQ->front = (qQ->front+1)%(qQ->arrayLen);qQ->queueLen--;return 1;}void traverseArrayQueue(struct arrayQueue * qQ){int i=0;i = qQ->front;//从队头开始遍历while( i != qQ->rear ){printf("qQ->pBase[%d] = %d\n",i,qQ->pBase[i]);i = (i+1)% (qQ->arrayLen);}        printf("\n");return;}
相关头文件:
#ifndef ARRAYQUEUE_H#define ARRAYQUEUE_H#include <stdio.h>#include <stdlib.h>#include <malloc.h>struct arrayQueue{    int * pBase;    int arrayLen;    int queueLen;    int front;    int rear;};void arrayQueueCreat(struct arrayQueue * qQ,int lengh);int arrayQueueIsFull(struct arrayQueue * qQ);int arrayQueueIsEmpty(struct arrayQueue * qQ);int enArrayQueue(struct arrayQueue * qQ,int val);int outArrayQueue(struct arrayQueue * qQ,int * pVal);void traverseArrayQueue(struct arrayQueue * qQ);#endif


0 0
原创粉丝点击