// 循环队列的实现
// 2015/3/30
#include
#include
#define MAXSIZE 5
typedef int datatype;
//定义队列结构体
typedef struct {
datatype a[MAXSIZE] ;
int front ;//队首
int rear ;//队尾
}sequence_queue;
//初始化函数
void init( sequence_queue *p )
{
p->front= p->rear= 0 ;
}
//判断是否为空队列
int is_empty( sequence_queue *p )
{
return (p->front == p->rear ) ? 1:0 ;
}
//显示函数
void display_queue(sequence_queue *p)
{
int i ;
if( is_empty(p) )//如果是空队列
{
printf("\n顺序队列是空的!\n") ; exit(1) ;
}
else
{
if( p->front > p->rear ) //判断队首是否大于队尾
for( i=p->front; i< ( p->rear+MAXSIZE ) ; i++)
printf("%d" ,p->a[ i%MAXSIZE ]);
else
for( i=p->front; i< p->rear ; i++ )
printf("%d \t" ,p->a[i]);
}
}
//插入函数,只能从队尾插入
void insert_queue(sequence_queue *p , datatype x )
{
if( (p->rear+1)%MAXSIZE == p->front )
{ printf("队列已满!\n") ; exit(1) ;}
p->a[p->rear] =x ;
p->rear = (p->rear+1)%MAXSIZE ;
}
//删除函数
void dele_queue(sequence_queue *p)
{
if( is_empty(p) )//如果是空队列
{
printf("\n顺序队列是空的!\n") ; exit(1) ;
}
p->front = ( p->front+1 ) %MAXSIZE ;
}
//主函数
int main()
{
sequence_queue sp ;
int x,flag=1;
init(&sp) ; //初始化
while(flag)
{
printf("请输入要插入的数!\n") ;
scanf("%d" ,&x) ;
//插入
insert_queue(&sp , x) ;
printf("是否继续插入!!继续插入(1) ,退出插入(0)\n") ;
scanf("%d" ,&flag) ;
}
display_queue(&sp);//显示
dele_queue(&sp) ;//删除
printf("\n") ;
display_queue(&sp);
}
本文详细介绍了如何使用C语言实现循环队列的数据结构,包括初始化、判断空队列、显示队列元素、插入元素及删除元素等关键操作。
1220

被折叠的 条评论
为什么被折叠?



