1. 程式人生 > >佇列基本操作

佇列基本操作

佇列:只允許在一端進行插入資料操作,在另一端進行刪除資料操作的特殊線性表,佇列具有先進先出
FIFO(First In First Out) 入佇列:進行插入操作的一端稱為隊尾 出佇列:進行刪除操作的一端稱為隊頭
Queue.h

#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>
#include<malloc.h>
#include<assert.h>
#include<stdlib.h>
typedef int QUDataType;

typedef struct QueueNode
{
	QUDataType _data;
	struct QueueNode* _next;
}QueueNode;

typedef struct Queue
{
	QueueNode* _front;
	QueueNode* _rear;
}Queue;

void QueueInit(Queue* q);
void QueueDestory(Queue* q);

void QueuePush(Queue* q, QUDataType x);
void QueuePop(Queue* q);
int QueueSize(Queue* q);
int QueueEmpty(Queue* q);
QUDataType QueueFront(Queue* q);
QUDataType QueueBack(Queue* q);

void QueuePrint(Queue* q);

//佇列的Pop實現是,先對隊頭進行判空,判空後,在對一個節點在分別處理,在刪除節點後,把隊尾置空

Queue.c

#define _CRT_SECURE_NO_WARNINGS 1

#include "queue.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->_front = q->_rear = NULL;
}

void QueueDestory(Queue* q)
{
	QueueNode* cur = NULL;
	assert(q);
	cur = q->_front;
	while (cur != NULL)
	{
		QueueNode* next = cur->_next;
		free(cur);
		cur = next;
	}
	q->_front = q->_rear = NULL;
}

QueueNode* QueueBuyNode(x)
{
	QueueNode* newnode = NULL;
	newnode = (QueueNode*)malloc(sizeof(QueueNode));
	newnode->_data = x;
	newnode->_next = NULL;
	return newnode;
}
void QueuePush(Queue* q, QUDataType x)
{
	assert(q);
	if (q->_front == NULL)
	{
		QueueNode* newnode = QueueBuyNode(x);
		q->_front = newnode;
		q->_rear = newnode;
	}
	else
	{
		QueueNode* newnode = QueueBuyNode(x);
		q->_rear->_next = newnode;
		q->_rear = newnode;
	}
}

void QueuePop(Queue* q)
{
	QueueNode* cur = NULL;
	assert(q);
	if (q->_front != NULL)
	{
		cur = q->_front->_next;
		free(q->_front);
		q->_front = cur;
		if (q->_front == NULL)
		{
			q->_rear = NULL;
		}
	}

}

int QueueSize(Queue* q)
{
	int count = 0;
	QueueNode* cur = NULL;
	assert(q);
	cur = q->_front;
	while (cur != NULL)
	{
		cur = cur->_next;
		count++;
	}
	return count;
}

int QueueEmpty(Queue* q)
{
	assert(q);
	if (q->_front == NULL)
		return 0;
	else
		return 1;
}

QUDataType QueueFront(Queue* q)
{
		return q->_front->_data;
}
QUDataType QueueBack(Queue* q)
{
		return q->_rear->_data;
}

void QueuePrint(Queue* q)
{
	assert(q);
	while (QueueEmpty(q))
	{
		printf("%d ", QueueFront(q));
		QueuePop(q);
	}
}