队列的数组结构
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Queue{
int * pBase;
int front;
int rear;
} QUEUE, * PQUEUE;
void initQueue ( PQUEUE pQueue, int length) ;
bool pushQueue ( PQUEUE pQueue, int value, int length) ;
bool isEmptyQueue ( PQUEUE pQueue) ;
bool isFullQueue ( PQUEUE pQueue, int length) ;
bool popQueue ( PQUEUE pQueue, int * pValue, int length) ;
void showQueue ( PQUEUE pQueue, int length) ;
int main ( int argc, const char * argv[ ] ) {
QUEUE queue;
int length = 6 ;
initQueue ( & queue, length) ;
pushQueue ( & queue, 1 , length) ;
pushQueue ( & queue, 12 , length) ;
pushQueue ( & queue, 19 , length) ;
showQueue ( & queue, length) ;
int value = 0 ;
if ( popQueue ( & queue, & value, length) ) {
printf ( "出栈成功,出栈的值为:%d\n" , value) ;
} else {
printf ( "出栈失败!" ) ;
}
showQueue ( & queue, length) ;
return 0 ;
}
void initQueue ( PQUEUE pQueue, int length)
{
pQueue-> pBase = ( int * ) malloc ( sizeof ( int ) * length) ;
if ( NULL == pQueue-> pBase) {
printf ( "分配空间失败!" ) ;
exit ( - 1 ) ;
} else {
pQueue-> rear = 0 ;
pQueue-> front = 0 ;
}
}
bool pushQueue ( PQUEUE pQueue, int value, int length)
{
if ( isFullQueue ( pQueue, length) ) {
return false;
} else {
pQueue-> pBase[ pQueue-> rear] = value;
pQueue-> rear = ( pQueue-> rear + 1 ) % length;
return true;
}
}
bool popQueue ( PQUEUE pQueue, int * pValue, int length)
{
if ( isEmptyQueue ( pQueue) ) {
return false;
} else {
* pValue = pQueue-> pBase[ pQueue-> front] ;
pQueue-> front = ( pQueue-> front + 1 ) % length;
return true;
}
}
bool isEmptyQueue ( PQUEUE pQueue)
{
if ( pQueue-> front == pQueue-> rear) {
return true;
} else {
return false;
}
}
bool isFullQueue ( PQUEUE pQueue, int length)
{
if ( pQueue-> front == ( pQueue-> rear + 1 ) % length) {
return true;
} else {
return false;
}
}
void showQueue ( PQUEUE pQueue, int length)
{
if ( isEmptyQueue ( pQueue) ) {
return ;
} else {
int tempFront = pQueue-> front;
printf ( "该队列里面的值分别为:" ) ;
while ( tempFront != pQueue-> rear) {
printf ( "%d " , pQueue-> pBase[ tempFront] ) ;
tempFront = ( tempFront + 1 ) % length;
}
printf ( "\n" ) ;
}
}
队列的链式结构