1. 程式人生 > >資料結構-佇列的實現

資料結構-佇列的實現

	資料結構是我們每個程式設計者必修的課程,它能最好的提高我們程式碼的質量,小面小編就在這分享一下實現佇列的方法吧。
	佇列與棧恰好相反,它的特點是元素先進先出,下面是原始碼!
#include<stdio.h>
#include<malloc.h>
struct node{
	int data;
	struct node *pnext;
};
struct queue{
	struct node *front;
	struct node *rear;
};
struct queue *phead = NULL;//定義全域性變數,方便呼叫
void createSpaceForQueue();
void initQueue(struct queue *phead);
void enQueue(struct queue *phead, int e);
void deQueue(struct queue *phead, int e);
void showQueue(struct queue *phead);
void clearQueue(struct queue *phead);
int main(){
	createSpaceForQueue();
	initQueue(phead);
	for(int i = 0; i < 5; i++){
		enQueue(phead, i);
	}
	showQueue(phead);
	deQueue(phead, 0);
	deQueue(phead, 0);
	deQueue(phead, 0);
	showQueue(phead);
	clearQueue(phead);
	return 0;
}
void createSpaceForQueue(){//為佇列分配記憶體空間
	phead = (struct queue*)malloc(sizeof(struct queue));//佇列的頭部是一個空結點;
	phead ->front=NULL;
	phead->rear = NULL;
}
void initQueue(struct queue *phead){//得到一個空佇列
	phead->front = phead->rear = (struct node*)malloc(sizeof(struct node));
	if (!phead->front){
		printf("空間分配錯誤,佇列初始化失敗!\n");
		return;
	}
	else{
		phead->front->pnext = NULL;
		printf("佇列初始化成功!\n");
	}
}
void enQueue(struct queue *phead,int e){//向佇列中插入元素
	struct node *pnew = NULL;
	pnew = (struct node*)malloc(sizeof(struct node));
	if (!pnew){
		printf("空間分配錯誤,元素%d插入失敗!", e);
	}
	else{
		pnew->data = e;
		pnew->pnext = NULL;
		phead->rear->pnext = pnew;/將新的結點連線在頭節點的後面;
		phead->rear = phead->rear->pnext;//頭節點指標後移,保證每次都指向最後一個結點;
		printf("元素%d插入成功!\n", e);
	}
}
void deQueue(struct queue *phead, int e){//刪除元素
	struct node *p = (struct node*)malloc(sizeof(struct node));
	if (phead->front == phead->rear){
		printf("此佇列為空,刪除失敗!\n");
	}
	else{
		p = phead->front->pnext;
		e = p->data;
		phead->front->pnext = p->pnext;
		if (phead->rear == p){
			phead->rear = phead->front;
		}
		free(p);
		printf("元素%d已從佇列上刪除!\n", e);
	}
}
void showQueue(struct queue *phead){//列印佇列中的元素
	struct node *pfind = NULL;
	pfind = phead->front->pnext;
	while (pfind != NULL){
		printf("%d ", pfind->data);
		pfind = pfind->pnext;
	}
	printf("\n");
}
void clearQueue(struct queue *phead){//清除結點,釋放記憶體;
	struct node *pcl = phead->front->pnext;
	struct node *p = NULL;
	while (pcl=NULL){
		p = pcl;
		free(p);
		pcl = pcl->pnext;
	}
	phead->front = NULL;
	phead->rear = NULL;
	printf("\n佇列被清除,記憶體已釋放!\n");
}