队列的一般操作

比较简单就直接上代码了

#include <stdlib.h>
#include <stdio.h>
typedef int Elem;
typedef struct Node
{
    Elem data;
    struct Node *pNext;
} Node;
typedef struct Queue
{
    Node *pFront;
    Node *pRear;
    int iLength;
} Queue;
/*
*   @createQueue    初始化一个队列
*   @enQueue        入队
*   @deQueue        出队 如果队列为空 返回-1
*   @destory        销毁一个队列
*   @isEmpty        判断队列是否为空
*   @getFront       返回队首元素
*   @size_          队列的大小
*/
//----队列的基本操作----
void creatQueue(Queue *que);
void enQueue(Queue *que, Elem data);
Elem deQueue(Queue *que);
void destory(Queue *que);
bool isEmpty(Queue *que);
Elem getFront(Queue *que);
int  size_(Queue *que);
void print(Queue *que);
int main()
{
    Queue que;
    creatQueue(&que);
    int arr[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    for(int i=0; i<9; i++)
    {
        enQueue(&que, arr[i]);
    }
    printf("原始队列:\n");
    print(&que);
    printf("--------------------\n");
    printf("出队:\n");
    deQueue(&que);
    print(&que);
    printf("99入队:\n");
    enQueue(&que, 99);
    print(&que);
    return 0;
}
void creatQueue(Queue *que)
{
    que->pFront = (Node*)malloc(sizeof(Node));  //新建头结点
    que->pRear  = que->pFront;                  //初始化队列
    que->pRear->pNext = NULL;
    que->iLength = 0;
}
void enQueue(Queue *que, Elem data)
{
    Node *pTmp = (Node*)malloc(sizeof(Node));   //初始化新节点
    pTmp->data = data;
    pTmp->pNext = NULL;
    que->pRear->pNext = pTmp;                   //队尾指向新节点
    que->pRear = pTmp;                          //更新队尾
    que->iLength++;
}
///不能只删除第一个元素, 还要移动Front
Elem deQueue(Queue *que)
{
    if(que->iLength)                        //队列非空
    {
        Node *pTmp = que->pFront;            //pTmp指向Front
        Elem data = pTmp->pNext->data;
        que->pFront = pTmp->pNext;           //把第一个元素隔离出来删掉
        free(pTmp);
        que->iLength--;
        return data;
    }
    return -1;

}
int length(Queue *que)
{
    return que->iLength;
}
bool isEmpty(Queue *que)
{
    return que->pFront == NULL;//这里不能是que->pFront == pRear;因为尾部已经后移了
}
void destory(Queue *que)
{
    Node *pCursor = que->pFront->pNext;
    free(que->pFront);
    while(pCursor)
    {
        Node *pTmp = pCursor->pNext;
        free(pCursor);
        pCursor = pTmp;
    }
}
Elem getFront(Queue *que)
{
    return que->pFront->pNext->data;
}
int size_(Queue *que)
{
    return que->iLength;
}
void print(Queue *que)
{
    Node *pCursor = que->pFront->pNext;
    while(pCursor)
    {
        if(pCursor->pNext)
            printf("%d ", pCursor->data);
        else
            printf("%d\n", pCursor->data);
        pCursor = pCursor->pNext;
    }
}

运行结果