1. 程式人生 > >佇列的定義和操作

佇列的定義和操作

一.定義

佇列是一種先進先出的邏輯結構。將允許刪除元素的一端稱為隊頭,允許插入元素的一端稱為隊尾。將沒有結點的佇列稱為空佇列。佇列中的每個結點包括資料元素本身和指向其後結點的指標。佇列的資料結構包括指向隊頭的指標、指向隊尾的指標和隊中結點的個數。

二.佇列結點的定義

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));
}