数组实现的队列
程序员文章站
2022-07-14 14:01:28
...
/*
* queue.c
*
* Created on: Dec 17, 2012
* Author: fsxchen
* 线性表实现的队列
*/
#include
#define MAXSIZE 100
typedef struct
{
int data[MAXSIZE];
int front;
int rear;
}SqQueue; //定义一个队列的结构体
void InitQueue(SqQueue *q)
{
q->front = 0;
q->rear = 0;
}
/*若队列没有满,则插入一个元素*/
void InsertQueue(SqQueue *q)
{
if((q->rear + 1) % MAXSIZE == q->front) /*此时队列为满,这里采用的是循环队列处理的*/
return;
int val;
printf("请输入你要插入的值");
scanf("%d", &val);
q->data[q->rear] = val; /*将值放到队尾*/
q->rear = (q->rear + 1) % MAXSIZE; /*队尾向后移动*/
return;
}
int DeleteQueue(SqQueue *q)
{
int n;
if(q->front == q->rear)
{
printf("队列为空");
return -1;
}
n = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return n;
}
void TraverseQueue(SqQueue *q)
{
if(q->front == q->rear)
{
printf("队列为空");
return ;
}
int ptr;
ptr = q->front;
while(ptr != q->rear)
{
printf("%d\t",q->data[ptr]);
++ptr;
}
}
int main()
{
SqQueue s;
InitQueue(&s);
InsertQueue(&s);
TraverseQueue(&s);
InsertQueue(&s);
TraverseQueue(&s);
printf("%d",DeleteQueue(&s) );
return 0;
}
只需要知道队列先进先出,只能在队尾增加,只能从队尾取出数据
转载于:https://my.oschina.net/fsxchen/blog/108646
下一篇: 循环队列的实现