一、Queue.h
#ifndef __Queue_h__
#define __Queue_h__
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <Windows.h>
typedef int DataType;
typedef struct QueueNode
{
DataType _data;
struct QueueNode* _next;
}QueueNode;
typedef struct Queue
{
QueueNode* _head;
QueueNode* _tail;
}Queue;
void QueueInit(Queue* q);
void QueueDestroy(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);
void QueuePrint(Queue* q);
#endif __Queue_h__
二、Queue.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"
void QueueInit(Queue* q)
{
assert(q);
q->_head = q->_tail = (QueueNode*)malloc(sizeof(QueueNode));
if (q->_head == NULL)
{
printf("初始化失败\n");
}
else
{
q->_head->_next = NULL;
printf("初始化成功\n");
}
}
void QueueDestroy(Queue* q)
{
assert(q);
while (q->_head)
{
q->_tail = q->_head->_next;
free(q->_head);
q->_head = q->_tail;
}
printf("销毁成功\n");
}
void QueuePush(Queue* q, DataType x)
{
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
if (newnode == NULL)
{
printf("插入失败\n");
}
else
{
newnode->_data = x;
newnode->_next = NULL;
q->_tail->_next = newnode;
q->_tail = newnode;
printf("插入成功\n");
}
}
void QueuePop(Queue* q)
{
if (q->_head == q->_tail)
{
printf("该队列为空\n");
}
else
{
QueueNode* next = q->_head->_next;
q->_head->_next = next->_next;
if (q->_tail == next)
{
q->_tail = q->_head;
}
free(next);
printf("删除成功\n");
}
}
DataType QueueFront(Queue* q)
{
if (q->_head == q->_tail)
{
printf("该队列为空\n");
}
else
{
return q->_head->_next->_data;
}
}
DataType QueueBack(Queue* q)
{
if (q->_head == q->_tail)
{
printf("该队列为空\n");
}
else
{
return q->_tail->_data;
}
}
size_t QueueSize(Queue* q)
{
assert(q);
QueueNode* cur = q->_head->_next;
int count = 0;
while (cur)
{
count++;
cur = cur->_next;
}
return count;
}
int QueueEmpty(Queue* q)
{
if (q->_head == q->_tail)
{
return 0;
}
return 1;
}
void QueuePrint(Queue* q)
{
if (q->_head == q->_tail)
{
printf("该队列为空\n");
}
else
{
QueueNode* cur = q->_head->_next;
while(cur)
{
printf("%d ", cur->_data);
cur = cur->_next;
}
printf("\n");
}
}