1.循环队列有几个初学者需要注意的地方:
(1)如何判断循环队列为空或者已满?
其实在程序设计的过程中是有很多方法来处理同一个问题的,就看编写代码者如何去处理。一般情况下,有两种方法来处理循环队列的这个问题:
a.在循环队列的定义过程中,用一个变量来记录当前队列中元素的个数;
b.利用 (Q->front + 1)%MaxSize == Q->rear来判断是否已满;利用Q->front == Q->rear来判断是否为空.因为(Q->front + 1)%MaxSize == Q->rear的缘故,这种方法最大使用队列空间的MaxSize - 1。
//
//
// 循环队列的实现
//
// 包括出队,入队等操作
//
//
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 20 // 队列的最大容量
typedef struct SeqQueue
{
int front ; // 队列头
int rear ; // 队列尾
int data[MaxSize] ; // 存储队列中的元素
} SeqQueue ;
void InitSeqQueue( SeqQueue * S )
{
S->front = 0 ;
S->rear = 0 ;
}
// 判断队列是否已满
bool is_full( SeqQueue * S )
{
if( (S->rear + 1) % MaxSize == S->front )
{
return true ;
}
else
{
return false ;
}
}
// 判断对列是否为空
bool is_empty( SeqQueue * S )
{
if( S->front == S->rear )
{
return true ;
}
else
{
return false ;
}
}
//入队
void EnQueue( SeqQueue * S , int elem )
{
if( !is_full( S ) )
{
S->data[S->rear] = elem ;
S->rear = ( S->rear + 1 ) % MaxSize ;
}
else
{
printf("队列已满,不能进行入队操作!") ;
exit(0) ;
}
}
// 出队操作
void DeQueue( SeqQueue * S , int * elem )
{
if( !is_empty( S ) )
{
*elem = S->data[S->front] ;
S->front = (S->front + 1 ) % MaxSize ;
}
else
{
printf("队列为空,不能进行出队操作!") ;
exit(0) ;
}
}
void Print( SeqQueue * S )
{
int i = S->front ;
while( i != S->rear )
{
printf("%d ",S->data[i] ) ;
i = ( i + 1 ) % MaxSize ;
}
printf("\n") ;
}
int main()
{
SeqQueue S ;
int elem ;
InitSeqQueue( &S ) ;
EnQueue( &S , 8 ) ;
EnQueue( &S , 4 ) ;
EnQueue( &S , 11 ) ;
EnQueue( &S , 7 ) ;
Print( &S ) ;
DeQueue( &S , &elem ) ;
printf("%d出队\n", elem ) ;
DeQueue( &S , &elem ) ;
printf("%d出队\n", elem ) ;
DeQueue( &S , &elem ) ;
printf("%d出队\n", elem ) ;
Print( &S ) ;
return 0 ;
}
2.链式队列
//
//
// 链式队列的实现 , 包括入队,出队等操作
//
//
///
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node
{
int elem ;
struct Node * next ;
} Node ;
typedef struct LinkQueue
{
Node * front ;
Node * rear ;
} LinkQueue ;
void InitQueue( LinkQueue * L )
{
L->front = NULL ;
L->rear = NULL ;
}
void EnQueue( LinkQueue * L , int elem )
{
Node * tmp = (Node*)malloc(sizeof(Node)) ;
if( !tmp )
{
printf("申请内存失败!") ;
exit(0) ;
}
tmp->elem = elem ;
tmp->next = NULL ;
if( L->front == L->rear && L->front == NULL )
{
L->front = tmp ;
L->rear = tmp ;
}
else
{
tmp->next = L->rear ;
L->rear = tmp ;
}
}
void DeQueue( LinkQueue * L , int * elem )
{
Node * p = L->rear ;
Node * q = p ;
while( p != L->front )
{
q = p ;
p = p->next ;
}
q->next = NULL ;
L->front = q ;
*elem = p->elem ;
free( p ) ;
}
void Print( LinkQueue * L )
{
Node * p = L->rear ;
while( p != L->front )
{
printf("%d ",p->elem ) ;
p = p->next ;
}
printf("%d\n" , p->elem ) ;
}
int main()
{
LinkQueue L ;
int elem ;
InitQueue( &L ) ; // 初始化
EnQueue( &L , 3 ) ;
EnQueue( &L , 6 ) ;
EnQueue( &L , 2 ) ;
EnQueue( &L , 9 ) ;
Print( &L ) ;
DeQueue( &L , &elem ) ;
printf("%d出队\n", elem ) ;
DeQueue( &L , &elem ) ;
printf("%d出队\n", elem ) ;
Print( &L ) ;
return 0 ;
}