数据结构-队列

Queue.h

#pragma once
#include
#include 
#include 
#include 
#include 

typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

void QueueInit(Queue * pq);//初始化队列
void QueueDestroy(Queue*pq);//销毁队列
void QueuePush(Queue* pq, QDataType x);//入队
void QueuePop(Queue* pq);//出队
QDataType QueueFront(Queue* pq);//取队首结点
QDataType QueueBack(Queue* pq);//取队尾结点
int QueueSize(Queue* pq);//统计队元素个数
bool QueueEmpty(Queue* pq);//判空

Queue.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"


void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}
void QueueDestroy(Queue* pq)
{
	QNode* cur = pq->phead;
	QNode* after = cur->next;
	while (cur)
	{
		free(cur);
		cur = after;
		if (cur)
		{
			after = after->next;
		}
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	QNode* newnode = malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail::");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->ptail == NULL)
	{
		assert(pq->phead == NULL);
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}
void QueuePop(Queue* pq)
{
	assert(pq);
	//队列为空
	assert(!QueueEmpty(pq));
	//当队列只有一个结点时,ptail会成为野指针,所以要分情况处理
	if (QueueSize(pq)==1)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
		pq->size = 0;
	}
	else
	{
		QNode* cur = pq->phead;
		pq->phead = pq->phead->next;
		free(cur);
		cur = NULL;
		pq->size--;
	}
}
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->phead);
	return pq->phead->data;
}
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}
int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	if (pq->phead == NULL && pq->ptail == NULL)
	{
		return true;
	}
	return false;
}

test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"
void test1()
{
	Queue pq;
	QueueInit(&pq);
	QueuePush(&pq, 0);
	QueuePush(&pq, 7);
	QueuePush(&pq, 2);
	QueuePush(&pq, 0);
	QueueDestroy(&pq);
}
int main()
{
	test1();
	return 0;
}

你可能感兴趣的:(数据结构,c++)