#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"
#define maxlen 20
typedef struct
{
int data[maxlen];
int front; /* 头指针 */
int rear; /* 尾指针,若队列不空,指向队列尾元素的下一个位置 */
}sqQueue;
int initqueue(sqQueue* Q)
{
Q->front = 0;
Q->rear = 0;
return 1;
}
int insert(sqQueue* Q, int value)
{
if ((Q->rear == maxlen-1 && Q->front == 0) || (Q->front - Q->rear == 1))
{
printf("队列满\n");
return 0;
}
Q->data[Q->rear] = value;
if (Q->rear == maxlen - 1)
{
Q->rear = 0;
}
else
{
Q->rear++;
}
return 1;
}
int delet(sqQueue* Q)
{
if (Q->front == Q->rear)
{
printf("队列空\n");
return 0;
}
if (Q->front == maxlen-1)
{
Q->front = 0;
}
Q->front++;
return 1;
}
int seeQueue(sqQueue Q)
{
int i, j;
i = Q.front;
j = Q.rear;
if (i == j)
{
printf("队列空\n");
return 0;
}
while (i!=j)
{
if (i == maxlen)
{
i = 0;
}
printf("%d ", Q.data[i]);
i++;
}
printf("\n");
return 1;
}
int getlength(sqQueue Q)
{
int i, j;
i = Q.front;
j = Q.rear;
if (j > i)
{
return j - i;
}
else
{
return maxlen - (i - j);
}
}
int main()
{
sqQueue Q;
initqueue(&Q);
for (int i = 0; i < 19; i++)
{
insert(&Q, i);
}
seeQueue(Q);
printf("长度为:%d\n", getlength(Q));
for (int j = 0; j < 17; j++)
{
delet(&Q);
}
seeQueue(Q);
printf("长度为:%d\n", getlength(Q));
insert(&Q, 20);
insert(&Q, 220);
delet(&Q);
seeQueue(Q);
printf("长度为:%d\n", getlength(Q));
}
顺序队列C语言实现
最新推荐文章于 2023-02-24 22:01:28 发布