数据结构-队列的实现

	数据结构是我们每个编程者必修的课程,它能最好的提高我们代码的质量,小面小编就在这分享一下实现队列的方法吧。
	队列与栈恰好相反,它的特点是元素先进先出,下面是源码!
#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;
		phead->front->pnext = NULL;
	phead->front = NULL;
	phead->rear = NULL;
	struct node *p = NULL;
	while (pcl!=NULL){
		p = pcl;
			pcl = pcl->pnext;
		free(p);
	}
	printf("\n队列被清除,内存已释放!\n");
}


发布了19 篇原创文章 · 获赞 7 · 访问量 7083

猜你喜欢

转载自blog.csdn.net/qq_43049583/article/details/83314651