顺序循环队列
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 5
typedef struct
{
int data[SIZE];
int front,rear;
}node;
node *init()
{
node *sq = (node *)malloc(sizeof(node));
sq->front = sq->rear = SIZE - 1;
return sq;
}
bool is_full(node *sq)
{
return (sq->rear + 1) % SIZE == sq->front;
}
bool is_empty(node *sq)
{
return sq->rear == sq->front;
}
bool push(node *sq, int num)
{
if( is_full(sq))
return false;
sq->rear = (sq->rear + 1) % SIZE;
sq->data[sq->rear] = num;
return true;
}
bool pop(node *sq, int *p)
{
if( is_empty(sq))
return false;
sq->front = (sq->front + 1) % SIZE;
*p = sq->data[sq->front];
return true;
}
void show(node *sq)
{
if(is_empty(sq))
return;
for(int i = (sq->front + 1) % SIZE; i != sq->rear + 1; (++i) % SIZE)
printf("%d\t",sq->data[i]);
printf("\n");
}
int main()
{
node *sq = init();
int n;
while(1)
{
if(scanf("%d", &n) == 1)
{
if( !push(sq,n) )
{
printf("push is failed\n");
}
else
{
show(sq);
}
}
else
{
if( !pop(sq, &n) )
{
printf("pop is failed\n");
}
else
{
printf("%d is pop\n", n);
show(sq);
}
}
while(getchar() != '\n');
}
return 0;
}
链式循环队列
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct node
{
int data;
struct node *next;
}linklist;
typedef struct
{
linklist *front,*rear;
}linkqueue;
linkqueue *init()
{
linkqueue *sq = (linkqueue *)malloc(sizeof(linkqueue));
sq->front = sq->rear = (linklist *)malloc(sizeof(linklist));
sq->rear->next == NULL;
return sq;
}
bool is_empty(linkqueue *sq)
{
return sq->front == sq->rear;
}
bool push(linkqueue *sq, int num)
{
linklist *ne = (linklist *)malloc(sizeof(linklist));
if(ne == NULL)
return false;
ne->data = num;
ne->next = NULL;
sq->rear->next = ne;
sq->rear = ne;
return true;
}
bool pop(linkqueue *sq, int *p)
{
if( is_empty(sq) )
return false;
linklist *tmp = sq->front->next;
*p = tmp->data;
sq->front->next = tmp->next;
free(tmp);
if(sq->front->next == NULL)
sq->rear = sq->front;
return true;
}
void show(linkqueue *sq)
{
linklist *tmp = sq->front->next;
for(; tmp != NULL; tmp = tmp->next)
printf("%d\t",tmp->data);
printf("\n");
}
int main()
{
linkqueue *sq = init();
int n;
while(1)
{
if(scanf("%d", &n) == 1)
{
if( !push(sq,n) )
{
printf("push is failed\n");
}
else
{
show(sq);
}
}
else
{
if( !pop(sq, &n) )
{
printf("pop is failed\n");
}
else
{
printf("%d is pop\n", n);
show(sq);
}
}
while(getchar() != '\n');
}
return 0;
}