队列的定义和操作

一.定义

队列是一种先进先出的逻辑结构。将允许删除元素的一端称为队头,允许插入元素的一端称为队尾。将没有结点的队列称为空队列。队列中的每个结点包括数据元素本身和指向其后结点的指针。队列的数据结构包括指向队头的指针、指向队尾的指针和队中结点的个数。

二.队列结点的定义

typedef int QDataType;
typedef struct QNode
{
	QDataType data;
	struct QNode* qnext;
}QNode;

三.队列的定义

typedef struct Queue
{
	struct QNode *Front;
	struct QNode *Rear;
	int size;
}Queue;

四.队列的操作

#pragma once
#include<stdlib.h>
#include<assert.h>
typedef int QDataType;
typedef struct QNode
{
	QDataType data;
	struct QNode* qnext;
}QNode;
typedef struct Queue
{
	struct QNode *Front;
	struct QNode *Rear;
	int size;
}Queue;

//初始化
void InitQueue(Queue *q)
{
	q->Front = q->Rear = NULL;
	q->size = 0;
}
//销毁
void QueueDestroy(Queue *q)
{
	q->Front = q->Rear = NULL;
	q->size = 0;
}
//打印
void QPrint(Queue q)
{
	if (q.size == 0)
	{
		printf("空队列\n");
		return;
	}
	QNode *p = q.Front;
	//如果队列中只有一个结点
	if (q.Front == q.Rear)
	{
		printf("%d\n", q.Rear->data);
		return;
	}
	for (; p != NULL; p = p->qnext)
	{
		printf("%d ", p->data);
	}
	printf("\n");
}

//入队列
void QueuePush(Queue *q, QDataType data)
{
	assert(q != NULL);
	QNode *qnode = (QNode*)malloc(sizeof(QNode*));
	if (qnode == NULL)
	{
		return;
	}
	qnode->data = data;
	qnode->qnext = NULL;
	//如果原来是空队列
	if (q->size == 0)
	{
		q->Front = q->Rear = qnode;
		q->size++;
	}
	else
	{
		q->Rear->qnext = qnode;
		q->Rear = qnode;
		q->size++;
	}
}
//出队列
void QueuePop(Queue *q)
{
	//如果是空队列
	if (q->size == 0)
	{
		printf("队列为空,出错\n");
		return;
	}
	//如果只有一个结点,修改。
	if (q->Front == q->Rear)
	{
		q->Rear = q->Front = NULL;
		q->size = 0;
		return;
	}
	QNode *del = q->Front;
	q->Front = q->Front->qnext;
	q->size--;
	//free(del);
}
//返回队首元素
QDataType QueueFront(Queue *q)
{
	if (q->size == 0)
	{
		printf("空队列,出错!\n");
		return 0;
	}
	return q->Front->data;
}
//返回队尾元素
QDataType QueueBack(Queue *q)
{
	assert(q);
	assert(q->Rear);
	return q->Rear->data;
}
//判断队列是否为空,为空,返回1;不为空,返回0.
int IsEmptyQ(Queue *q)
{
	if (q->size == 0)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
// 返回数据个数 
int QueueSize(Queue *q)
{
	int count = 0;
	if (q->size == 0)
	{
		return 0;
	}
	QNode *p = q->Front;
	for (; p != NULL; p = p->qnext)
	{
		count++;
	}
	return count;
}
void test2()
{
	Queue q;
	InitQueue(&q);
	QPrint(q);
	QueuePush(&q, 100);
	QueuePush(&q, 200);
	QPrint(q);
	printf("%d\n", QueueSize(&q));
}

猜你喜欢

转载自blog.csdn.net/smell201611010513/article/details/83445378