【数据结构】循环队列 C语言实现

"Queue.h"

#include "Queue.h"
#include <stdio.h>
#include <stdlib.h>
status Queue_init(SqQueue *Q)
{
    Q->data = (char*)malloc(sizeof(char)*MAXSIZE);
    Q->front = 0;
    Q->rear = 0;
    return OK;
}

status Queue_In(SqQueue *Q,char e) //进入队列
{
    if((Q->rear +1)%MAXSIZE ==Q->front)
    {
        printf("队列已满");
        return ERROR;
    }
    Q->data[Q->rear] = e;
    Q->rear =(Q->rear+1)%MAXSIZE;
    return OK;
}

char Queue_Out(SqQueue *Q)
{
    char e;
    if(Q->front == Q->rear)
    {
        printf("队列为空");
        return ERROR;
    }
    e = Q->data[Q->front];
    Q->front = (Q->front+1)%MAXSIZE;
    return e;
}
void Print_Queue(SqQueue Q)
{
    int i=Q.front;
    printf("队列:\n");
    while(i!= Q.rear)
    {
        printf("%c",Q.data[i]);
        i = (i+1)%MAXSIZE;
    }
    printf("\n");
}

int Queue_length(SqQueue Q)
{
    return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}

"main.c"

#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
#include <string.h>

int main()
{
    SqQueue Q;
    char c;
    char rec[MAXSIZE] ;
    int i;
    Queue_init(&Q);
    printf("请输入一个字符串:\n");
    gets(rec);
    for(i=0;rec[i]!= '\0';i++)
    {
        Queue_In(&Q,rec[i]);
    }
    Print_Queue(Q);
    printf("队长为:%d\n",Queue_length(Q));
    printf("!加入游戏\n");
    Queue_In(&Q,'!');
    printf("%c退出了游戏\n",Queue_Out(&Q));
    Print_Queue(Q);
    return 0;
}

posted @ 2018-05-04 08:59  金舰  阅读(452)  评论(0编辑  收藏  举报