首页 » Program » C/C++ » 正文

Sequential queue

顺序队列是一种先进先出的数据结构,利用头指针和尾指针操作元素

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

typedef struct
{
    int queue[10];
    int front;
    int rear;
} qqtype;

//初始化队列
void init(qqtype *q)
{
    q->front = -1;
    q->rear = -1;
}

int enterline(qqtype *q,int x)   //入队
{
    if (q->rear==9)   //0~9 10个元素
        return 0;
    else
        {
            q->rear++;     //下标从要0开始
            q->queue[q->rear]=x;
            return 1;
        }
}

int main()
{
    int ch,sign;
    qqtype *q;
    q = (qqtype *)malloc(sizeof(qqtype));
    init(q);
    printf("creat success\n");
    printf("please input the data\n");
    scanf("%d",&ch);
    while (ch!=-1)
        {
            if ((sign = enterline(q,ch))!=1)
                break;
            scanf("%d",&ch);
        }
    printf("output the data\n");
    while (q->front!=q->rear)      //队满时,front为-1,rear为9
        {
            q->front++;
            printf("%d ",q->queue[q->front]);
        }
    printf("\n");
    return 0;
}

赞 (0)

Comment