欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

循环队列 C语言实现

程序员文章站 2022-04-09 21:08:21
"Queue.h" "main.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;
}

循环队列 C语言实现