线性结构--->循环队列的顺序储存实现

循环队列的顺序储存


算法介绍

直接写循环队列

创建
入列
出列
遍历
队列的长度

例如清空, 销毁….之类的操作都没有写
以后的有时间再补充


一些疑问

一次听课,看书时, 都没有懂, 为什么,加那么多 求余的, 下面想想写写, ~~~>

    -

第一次代码实现——–2016年-10月-4号 ———–

没有加注释...会补上的......

------------------------
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

#define OK 1 
#define ERROR 0

/**
*定义顺序存储的最大长度为 6 
*虽然最大长度为 6 
*但实际最大存储量为 5
*/
#define MAXSIZE 6 

typedef int Status;
typedef int ElemType;
/**
*定义struct类型,
*没有采用书上采用的指针类型
*/
typedef struct Node{
    ElemType *data; /*数据域 */
    int front;/*定义头指针*/
    int rear;/*定义尾指针*/
} Queue, *pQueue;

/**函数声明 */
Status createQueue(pQueue Q);
Status enQueue(pQueue Q, ElemType e);
Status deleteQueue(pQueue Q, ElemType *e);//为了将出列的元素的值返回, 所以这里使用指针 
void display(pQueue Q);
int QueueLength(pQueue Q);

/**定义主函数*/

int main() {
    Queue Q;
    ElemType delete_e; /*存放出列的元素的值*/
    int queue_length;
    createQueue(&Q);
    enQueue(&Q, 0);
    enQueue(&Q, 1);
    enQueue(&Q, 2);
    enQueue(&Q, 3);
    enQueue(&Q, 4);

    printf("遍历入列后的队列: ");
    display(&Q);

    if( deleteQueue(&Q, &delete_e) ){
        printf("出列成功, 出列的元素为 %d\n 遍历出列后的队列: ", delete_e);
        display(&Q);    
    }
    printf("对列的长度为: %d", QueueLength(&Q));
    return 0; 
}
int QueueLength(pQueue Q){
    return (Q->rear - Q->front + MAXSIZE) % MAXSIZE;
}
Status createQueue(pQueue Q){
    Q->data = (ElemType*)malloc(sizeof(ElemType)*MAXSIZE);
    if(Q->data == NULL){

        printf("内存分配失败, 队列创建失败!!!\n");
        /*这里也可以写成不终止程序, 改为返回 ERROR 也是可以的*/
        //return ERROR; 
        exit(-1);
    }
    /*将头指针,尾指针 都指向第一个存储位置*/
    Q->front = 0;
    Q->rear = 0;
    return OK;
} 
Status enQueue(pQueue Q, ElemType e){
    /* 先判断队列是否已满 */
    if( (Q->rear + 1) % MAXSIZE == Q->front ){
        printf("队列已满, 入列失败!!\n");
        return ERROR;
    }

    Q->data[Q->rear] = e;

    /*rear指针向后移动 一个位置, 若到最后, 则移动到 数组头部*/
    Q->rear = (Q->rear + 1) % MAXSIZE;

    return OK;
}
Status deleteQueue(pQueue Q, ElemType *e){
    if(Q->front == Q->rear){/*队列为空的判断*/
        printf("队列为空, 出列失败!!\n");
        return ERROR; 
    }
    *e = Q->data[Q->front];
    Q->front = (Q->front+1) % MAXSIZE;
    return OK;
}

/*队列的遍历*/
void display(pQueue Q){
    int f = Q->front; 
    int r = Q->rear;
    /*遍队列结束的条件就是 头指针尾指针 指在相同位置*/
    while( f != r ) {
        printf("%-4d", Q->data[f]);
        f = (f+1) % MAXSIZE;
    }
    putchar('\n');

    return ; //标志着函数体的结束 
}


仅供参考 ,有错误望指出.

有大神路过请指点一下。 菜鸟求飞 !!!
有什么疑问 也可以在 下边 提问 ! (有点托大了)或者发邮件
E-Mail:[email protected]

猜你喜欢

转载自blog.csdn.net/qq_32603745/article/details/52738196