【数据结构】队列的实现

文章目录

    • Queue.h
    • Queue.c
    • Test.c

Queue.h

#ifndef __QUEUE_H__
#define __QUEUE_H__


#include
#include
#include
#include


typedef int DataType;


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


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

void QueueInit(Queue* q);
void QueueDestory(Queue* q);
void QueuePush(Queue* q, DataType x);
void QueuePop(Queue* q);
DataType QueueFront(Queue* q);
DataType QueueBack(Queue* q);
size_t QueueSize(Queue* q);
int QueueEmpty(Queue* q);
#endif

Queue.c

#include "Queue.h"

void QueueInit(Queue* q)
{
	assert(q);
	q->_front = NULL;
	q->_back = NULL;
}
void QueueDestory(Queue* q)
{
	assert(q);
	QueueNode* cur;
	QueueNode* tmp;
	cur = q->_front;
	while (cur)
	{
		tmp = cur->_next;
		free(cur);
		cur = tmp;
	}
	q->_front = q->_back = NULL;
}
QueueNode* BuyQueueNode(DataType x)
{
	QueueNode* cur;
	cur = (QueueNode*)malloc(sizeof(QueueNode));
	if (cur == NULL)
	{
		perror("use malloc");
	}
	cur->_data = x;
	cur->_next = NULL;
	return cur;
}
void QueuePush(Queue* q, DataType x)
{
	assert(q);
	QueueNode* cur;
	if (q->_front == NULL)
	{
		cur = BuyQueueNode(x);
		q->_back = cur;
		q->_front = cur;
	}
	else
	{
		cur = BuyQueueNode(x);
		q->_back->_next = cur;
		q->_back = cur;
	}
}
void QueuePop(Queue* q)
{
	assert(q);
	QueueNode*next = q->_front->_next;
	free(q->_front);
	q->_front = next;
}
DataType QueueFront(Queue* q)
{
	assert(q);
	if (q->_front != NULL)
		return q->_front->_data;
	else
		return 0;
}
DataType QueueBack(Queue* q)
{
	assert(q);
	if (q->_back != NULL)
		return q->_back->_data;
	else
		return 0;
}
size_t QueueSize(Queue* q)
{
	assert(q);
	int count = 0;
	if (q->_front == NULL)
		return 0;
	else
	{
		QueueNode* cur;
		cur = q->_front;
		while (cur)
		{
			count++;
			cur = cur->_next;
		}
		return count;
	}
}
int QueueEmpty(Queue* q)
{
	assert(q);
	return q->_front == NULL ? 0 : 1;
}

Test.c

#include "Queue.h"

void Test()
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q, 1);
	QueuePush(&q, 2);
	QueuePush(&q, 3);
	QueuePush(&q, 4);
	QueueDestory(&q);
	printf("%d ", QueueFront(&q));
	printf("%d ", QueueBack(&q));
	/*printf("Stack's size : %d \n", QueueEmpty(& q));*/
	printf("Stack's size : %d \n", QueueSize(&q));
	while (QueueEmpty(&q) != 0)
	{
		printf("%d ", QueueFront(&q));
		QueuePop(&q);
	}
	printf("\n");
}


int main()
{
	Test();
	system("pause");
}

你可能感兴趣的:(神兵利剑)