不是只有排序,二叉樹才叫數據結構,面試栽在基本的數組和隊列,鏈表,棧的有的是!!!本文對循環隊列的重要操作作出總結。注:為了避免隊列空和滿兩個狀態混淆,
采用空閑一個位置的方式,即N個元素空間的循環隊列最多只能存放N-1個有效元素。這也是大多數教材的做法。
1) 循環隊列初始化:front=rear=0;
2)入隊操作:rear=(rear+1)%size;
3)出隊操作:front=(front+1)%size;
4)判斷是否為空隊列:front==rear;
5)判斷隊列是否已滿:front=(rear+1)%size;
6)遍歷隊列各元素。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdbool.h> //注意使用布爾類型時,需要引入此頭文件
/*******************************************************************************************************************
定義循環隊列的結構體。注:循環隊列是在數組的基礎上實現的,所以需要一個指向首元素的指針,另外頭和尾用int來表示相對偏移量即可。
********************************************************************************************************************/
typedef struct Queue
{
int * qBase;
int front;
int rear;
}QUEUE;
void initQueue(QUEUE *pq);
void enQueue(QUEUE *pq , int value);
bool isemptyQueue(QUEUE *pq);
bool is_fullQueue(QUEUE *pq);
void deQueue(QUEUE *pq , int *value);
void traverseQueue( QUEUE *pq);
/***************************************** 主函數測試入口 ********************************************/
int main(){
int val;
QUEUE queue = {NULL,0,0} ;
initQueue(&queue);
enQueue(&queue,4);
enQueue(&queue,5);
enQueue(&queue,6);
enQueue(&queue,7);
enQueue(&queue,72);
enQueue(&queue,42);
traverseQueue(&queue);
deQueue(&queue , &val);
deQueue(&queue , &val);
traverseQueue(&queue);
enQueue(&queue,55);
enQueue(&queue,65);
traverseQueue(&queue);
return 0;
}
/**************************************初始化一個空的循環隊列 ******************************************/
void initQueue(QUEUE *pq){
pq->qBase = (int *)malloc(sizeof(int)*6);
if(pq->qBase == NULL){
printf("內存分配失敗!\n");
exit(-1);
}
pq->front = pq->rear = 0;
}
/***************插入一個新元素 注:插入前需要先判斷該隊列是否已滿,避免覆蓋有效數據******************/
void enQueue(QUEUE *pq , int value){
if(is_fullQueue(pq)){
printf("循環隊列已滿,拒絕插入%d!\n",value);
}
else{
pq->qBase[pq->rear] = value;
pq->rear = (pq->rear + 1)%6 ;
printf("\n %d 入隊 \n" , value);
}
}
/************** 刪除一個元素,並通過指針返回該數 注:刪除前要判斷該隊列是否為空。*******************/
void deQueue(QUEUE *pq , int *value){
if(isemptyQueue(pq)){
printf("循環隊列已空!");
}
else{
*value = pq->qBase[pq->front];
printf("\n %d 出隊 \n",*value);
pq->front = (pq->front + 1)%6 ;
}
}
/************************************ 判斷循環隊列是否為空 ************************************/
bool isemptyQueue(QUEUE *pq){
if(pq->front == pq->rear){
return true;
}
else
return false;
}
/************************************ 判斷循環隊列是否已滿 ************************************/
bool is_fullQueue(QUEUE *pq){
if((pq->rear +1)%6 == pq->front){
return true;
}else
return false;
}
/************************************* 遍歷循環隊列中的各元素 *************************************/
void traverseQueue( QUEUE *pq){
if(isemptyQueue(pq)){
printf("循環隊列為空!\n");
exit(0);
}
printf("當前循環隊列 :\n");
printf("front是%d,rear是%d :\n",pq->front,pq->rear);
int tail = pq->front ;
while(tail != pq->rear){
printf(" %d ",pq->qBase[tail]);
tail = (tail + 1)%6;
}
}
