順序隊列——隊列的順序表示和實現

隊列的順序表表示:

#include<cstdio>
#include<cstdlib> 
#define QElemType int 
#define Status int 
#define QUEUE_INIT_SIZE 100	//初始空間分配量
#define QUEUEINCREMENT	10		//存儲空間分配增量 

using namespace std;
//隊列的結構
typedef struct {
	QElemType *front;	
	QElemType *rear;		
	int queuesize;
}SqQueue; 
//初始化隊列 
/**
說明,這裏使用C語言的malloc和realloc
除此之外,還可以使用c++的new運算符(	S.base = new SElemType[MAXSIZE];)
但是,new運算符在給定一個定長數組初始化後,長度變不能改變(c++沒有realloc函數) 
改進有兩個方法,
(1)、在初始化時,使用vector變長數組代替數組
(2)、新建一個更大的數組,將原有的元素複製過去(realloc就是這個原理) 
*/ 
Status InitQueue(SqQueue &Q){
	Q.front = Q.rear = (QElemType *)malloc(QUEUE_INIT_SIZE*sizeof(QElemType));
	if(!Q.front){
		printf("內存分配失敗\n");
		return 0;
	}
	Q.queuesize = QUEUE_INIT_SIZE;
	return 0; 
}

//獲取隊列元素個數
int QueueLength(SqQueue Q){
	printf("鏈表長度爲%d\n",Q.rear-Q.front); 
	return Q.rear-Q.front; 
} 

//入隊
Status EnQueue(SqQueue &Q,QElemType e){
	//判斷內存空間是否已滿
	if(Q.rear - Q.front == QUEUE_INIT_SIZE){
		Q.front = (QElemType *)realloc(Q.front,(Q.queuesize+QUEUEINCREMENT)*sizeof(QElemType));
		if(!Q.front){
			printf("內存分配失敗\n");
			return 0; 
		}
		Q.rear = Q.front + Q.queuesize;		//更新隊尾指針
		Q.queuesize += QUEUEINCREMENT;		//更新隊的最大容量 
	} 
	*Q.rear++ = e;		//將元素插入隊尾並使指針後移 
	printf("入隊成功\n"); 
	return 0; 
} 

//出隊	順序表沒有釋放內存,不能使用free(); 
Status DeQueue(SqQueue &Q,QElemType e){
	//判空
	if(Q.front == Q.rear){
		printf("隊列爲空\n");
		return 0;
	}
	QElemType *p = Q.front;
	e = *Q.front++;		//獲取隊頭元素 
	printf("元素%d出隊\n",e);
	return 0;
}  

//創建棧,就是重複的將元素入棧(當然也可以單獨寫一個創建的函數)
void CrQueue(SqQueue &Q,int n){
	InitQueue(Q);
	for(int i=0;i<n;i++){
		int e;
		scanf("%d",&e); 
		EnQueue(Q,e);
	}
	printf("創建成功\n");
}  

//判空
Status QueueEmpty(SqQueue Q){
	if(Q.front == Q.rear){
		printf("隊列爲空\n");
		return true;
	}else{
		printf("隊列不爲空\n");
		return false;	
	}
}  

//獲取隊頭元素
Status GetHead(SqQueue Q,QElemType e){
	if(Q.front == Q.rear){
		printf("隊列爲空\n");
		return 0;
	}
	e = *Q.front;	//隊頭元素之前有一個空的頭結點 
	printf("隊頭元素爲:%d\n",e);
	return 0; 
} 

//遍歷
Status QueueTraverse(SqQueue Q){
	printf("遍歷開始:");
	QElemType *p = Q.front;		//隊頭元素之前有一個空的頭結點
	while(p != Q.rear){	//當p沒有到達隊尾指針 
		printf("%d ",*p);
		p++;
	} 
	printf("\n"); 
	return 0; 
}

//置空
Status ClearQueue(SqQueue &Q){
	Q.rear = Q.front;	
	printf("置空操作成功\n");
	return 0; 
} 

//銷燬
Status DestoryQueue(SqQueue &Q){ 
	Q.front = NULL;		//棧底指針賦空 
	Q.rear = NULL;		//棧頂指針賦空
	Q.queuesize = 0;		//棧最大容量置爲0
	free(Q.front);	//銷燬連續空間
	printf("銷燬成功");
	return 0; 
} 
  

int main(){
	int n;
	QElemType value1,value2;
	SqQueue Q;
	printf("請輸入隊列元素個數:");
	scanf("%d",&n);
	CrQueue(Q,n);
	QueueTraverse(Q); 
	QueueLength(Q);
	GetHead(Q,value1); 
	DeQueue(Q,value2);
	QueueTraverse(Q);
	ClearQueue(Q);
	DestoryQueue(Q);
	return 0; 
} 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章