线性结构之链队


队列,是只能通过访问它的一端来实现数据存储和检索的一种线性数据结构。对于队列的修改要按照先进先出的原则进行,因此,队列又被称为先进先出(FIFO)的线性表。

链队,队列的链式存储。

基本方法有:

  1. 初始化:创建一个空的队列。
  2. 判断队列是否为空:如果队列为空,则返回”真“,否则返回”假“。
  3. 入队:将元素x加入到队列的队尾,并更新队尾指针。
  4. 出队:将队头元素从队列中删除,并更新队头指针。
  5. 读取队头元素:返回对头元素的值,但不更新队头指针。

C语言实现

#define TRUE 1
#define FALSE 0
#define ERROR -1
#define NULL -2
typedef int bool;
typedef int ElementType;
typedef struct Node *PtrToNode;

Queue CreateQueue(int MaxSize);
bool IsFull(Queue Q);
bool IsEmpty(Queue Q);
bool AddQ(Queue Q, ElementType X);
ElementType DeleteQ(Queue Q);

struct Node { /* 队列中的结点 */
    ElementType Data;
    PtrToNode Next;
};
typedef PtrToNode Position;
 
struct QNode {
    Position Front, Rear;  /* 队列的头、尾指针 */
    int MaxSize;           /* 队列最大容量 */
};
typedef struct QNode *Queue;
 
bool IsEmpty( Queue Q )
{
    return ( Q->Front == NULL);
}
 
ElementType DeleteQ( Queue Q )
{
    Position FrontCell; 
    ElementType FrontElem;
     
    if  ( IsEmpty(Q) ) {
        printf("队列空");
        return ERROR;
    }
    else {
        FrontCell = Q->Front;
        if ( Q->Front == Q->Rear ) /* 若队列只有一个元素 */
            Q->Front = Q->Rear = NULL; /* 删除后队列置为空 */
        else                     
            Q->Front = Q->Front->Next;
        FrontElem = FrontCell->Data;
 
        free( FrontCell );  /* 释放被删除结点空间  */
        return  FrontElem;
    }
}

应用

  1. 排队买 XXX
  2. 医院的挂号系统