队列基本操作总结

定义数据结构

typedef int DataType;
//定义队列结点类型
typedef struct QueueNode
{
    struct QueueNode* _next;
    DataType _data;
}QueueNode;
//定义队列类型
typedef struct Queue
{
    QueueNode* front;//队头
    QueueNode* rear;//队尾
}Queue;

各个函数声明

//初始化队列
void QueueInit(Queue* pq);
//销毁队列
void QueueDestroy(Queue* pq);
//开辟新的结点
QueueNode* BuyQueueNode(DataType x);
//入队操作(队尾)
void QueuePush(Queue* pq, DataType x);
//出队操作(队头)
void QueuePop(Queue* pq);
//取队头元素
DataType QueueFront(Queue* pq);
//判断队是否为空,空返回0,非空返回1
int QueueEmpty(Queue* pq);
//求队列的大小
int QueueSize(Queue* pq);

函数实现

#include"Queue.h"
//初始化队列
void QueueInit(Queue* pq)
{
    assert(pq);
    pq->front = NULL;
    pq->rear = NULL;
}
//销毁队列
void QueueDestroy(Queue* pq)
{
    assert(pq);
    QueueNode* cur = pq->front;
    while (cur)
    {
        QueueNode* tmp = cur->_next;
        free(cur);
        cur = tmp;
    }
    pq->front = pq->rear = NULL;
}
//开辟新的结点
QueueNode* BuyQueueNode(DataType x)
{
    QueueNode* tmp = (QueueNode*)malloc(sizeof(QueueNode));
    if (tmp == NULL)
    {
        perror("use malloc");
    }
    tmp->_next = NULL;
    tmp->_data = x;
    return tmp;
}
//入队操作(队尾)
void QueuePush(Queue* pq, DataType x)
{
    assert(pq);
    if (pq->front == NULL)
    {
        QueueNode *next = BuyQueueNode(x);
        pq->rear = next;
        pq->front = next;
    }
    else
    {
        QueueNode *next = BuyQueueNode(x);
        pq->rear->_next = next;
        pq->rear = next;
    }
}
//出队操作(队头)
void QueuePop(Queue* pq)
{
    assert(pq);
    QueueNode* next = pq->front->_next;
    free(pq->front);
    pq->front = next;
}
//取队头元素
DataType QueueFront(Queue* pq)
{
    assert(pq);
    return pq->front->_data;
}
//判断队是否为空,空返回0,非空返回1
int QueueEmpty(Queue* pq)
{
    assert(pq);

    return pq->front == NULL ? 0 : 1;
}
//求队列的大小
int QueueSize(Queue* pq)
{
    int size = 0;
    assert(pq);
    QueueNode* cur = pq->front;
    while (cur)
    {
        size++;
        cur = cur->_next;
    }
    return size;
}

猜你喜欢

转载自blog.csdn.net/hansionz/article/details/81636644