数组实现的简单循环队列

时间:2022-05-17 17:37:15
#include <stdio.h>
#include <stdlib.h>
//设计一个队列的类型
typedef int Item;
struct queue
{

 Item * head;
 Item * tail;
 int lenth;
 int size;
};
void deletes(struct queue *que);
void insert(struct queue *que,Item k);
void prin(struct queue* que);
Item * add;
int main(void)
{

 //initialize the queue
 int arr[5];
 Item n[5]={1,2,3,4,5};
 Item a=10;  
 struct queue *que;
 que=(struct queue*)malloc(sizeof(struct queue));
 add=&arr[0];
 que->tail=que->head =&arr[0];
 que->size =0;
 que->lenth =5;
 for(int i=0;i<5;i++)
  insert(que,n[i]);//add an item
 prin(que);  //print the queue 
 deletes(que);//delete an item from the head
 prin(que);
 insert(que,a);
 prin(que);
 deletes(que);
 prin(que);
 insert(que,a);
 prin(que);
 insert(que,a);
 prin(que);
 return 0;
}
void deletes(struct queue *que)
{
 printf("delete an item:%d\n",*(que->head));
 (que->head)++;
 (que->size)--;
}
  
void insert(struct queue * que,Item k)
{
 printf("insert an item: %d into the queue\n",k);
 if(que->size==que->lenth )
 {
  printf("queue is full so that can not add an item\n");
  exit(1);
 } 
 *(que->tail )=k;
 (que->tail )++;
 (que->size )++;
 if(que->size==que->lenth )
  printf("queue is full\n");
 if(que->tail ==(add+que->lenth ))
  que->tail = add;
}
void prin(struct queue* que)
{
 printf("print all of items in the queue:\n");
 Item *ss;
 ss=que->head ;
 do
 {  
  printf("%d,",*(ss));
  ss++;
   if((ss)==(add +que->lenth ))
   ss =add ;
 }while(ss!=que->tail);
 printf("\n");
}