您的位置:首页 > 其它

队列的创建,入队,出队,遍历

2015-03-05 15:02 387 查看
#include <stdio.h>
#include <malloc.h>

typedef struct queue{
	int * pBase;
	int front;
	int rear;
}QUEUE;

void init(QUEUE *);
bool enQueue(QUEUE *,int);
bool IsFullQueue(QUEUE *);
bool traverseQueue(QUEUE *);
bool IsEmptyQueue(QUEUE *); 
bool outQueue(QUEUE *,int *);

int main(void){
	QUEUE Q;
	int qVal;
	init(&Q); 
	enQueue(&Q,1);
	enQueue(&Q,2);
	enQueue(&Q,3);
	enQueue(&Q,4);
	enQueue(&Q,5);
	traverseQueue(&Q);
	if ( outQueue(&Q,&qVal) ){
		printf("出队成功,出队的元素是:%d\n",qVal);
		
	}
	else
  		printf("出队失败!"); 
	traverseQueue(&Q);
	
	

} 

void init(QUEUE *qQ){
	qQ->pBase = (int *)malloc(sizeof(int)*6);
	qQ->front = qQ->rear = 0;
	return; 
}
bool IsFullQueue(QUEUE *qQ){
	if ( (qQ->rear+1)%6 == qQ->front ){   //front和rear紧挨着就能判断队列已经满了 
		return true;
	}
	else
	    return false;
}

bool enQueue(QUEUE *qQ,int pVal){
	if (IsFullQueue(qQ)){
		return false;
	}
	else{ 
	    qQ->pBase[qQ->rear] = pVal;
	    qQ->rear = (qQ->rear+1)%6;
	    return true;
 	} 
	    
}

bool traverseQueue(QUEUE *qQ){
	if (IsEmptyQueue(qQ)){
		return	false;
	}
	else {
		   int i = qQ->front; //int i = 0;这样写就错了,出队以后还是从第一个开始  
		while(i	!= qQ->rear){
			printf("%d\n",qQ->pBase[i]);
			i = (i+1)%6;
				
		}
		
	}
	
	return true;
	    
}

bool IsEmptyQueue(QUEUE *qQ){
	if (qQ->front == qQ->rear){     //注意判断是否满的条件和是否为空的条件 
		return true;
	}
	else 
	    return false;
}

bool outQueue(QUEUE *qQ,int *qVal){
	if (IsEmptyQueue(qQ)){
		return false;
	}
	else{
		*qVal = qQ->pBase[qQ->front];
		qQ->front = (qQ->front+1)%6;   //后移一个
		return true;
	} 
		
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: