대기 열의 링크 구현 (C 언어)
                                            
 7611 단어  데이터 구조 구현
                    
#include <stdio.h>
#include <stdlib.h>
struct QueueRecord;
typedef struct QueueRecord *Queue;
typedef struct Node *QueueNode;
typedef int ElementType;
//          
#define MAXSIZE 100
//           
struct Node
{
    ElementType Data;
    QueueNode Next;
};
//          
struct QueueRecord
{
    int Size;
    QueueNode Front;
    QueueNode Rear;
};
//           
void MakeEmpty(Queue Q)
{
    Q->Front->Next = Q->Rear->Next = NULL;
    Q->Size = 0;
}
//     
Queue CreateQueue()
{
    //        ,         
    Queue Q;
    Q = malloc(sizeof(struct QueueRecord));
    Q->Front = Q->Rear = malloc(sizeof(struct Node));
    if (Q == NULL || Q->Rear == NULL || Q->Front == NULL)
    {
        printf("queue malloc failed.
");
        return NULL;
    }
    MakeEmpty(Q);
    return Q;
}
//         
int IsEmpty(Queue Q)
{
    return Q->Size == 0;
}
//         
int IsFull(Queue Q)
{
    return Q->Size == MAXSIZE;
}
//   
void Enqueue(ElementType X, Queue Q)
{
    if (IsFull(Q))
    {
        printf("queue is full.
");
        return;
    }
    Q->Size++;
    QueueNode Tmp = malloc(sizeof(struct Node));
    if (Q->Rear == NULL)
    {
        printf("Q->Rear malloc failed.
");
        return;
    }
    Tmp->Data = X;
    Tmp->Next = NULL;
    Q->Rear->Next = Tmp;
    Q->Rear = Tmp;
}
//   
void Dequeue(Queue Q)
{
    if (IsEmpty(Q))
    {
        printf("queue is full.
");
        return;
    }
    Q->Size--;
    QueueNode Tmp = Q->Front->Next;
    Q->Front->Next = Tmp->Next;
    free(Tmp);
}
//     front  ,    front
ElementType FrontAndDequeue(Queue Q)
{
    if (IsEmpty(Q))
    {
        printf("queue is empty.
");
        return 0;
    }
    ElementType Tmp = Q->Front->Next->Data;
    Dequeue(Q);
    return Tmp;
}
//       
void FreeQueue(Queue Q)
{
    while (IsEmpty(Q) == 0)
    {
        Dequeue(Q);
    }
    free(Q->Front);
}
//       
void PrintQueue(Queue Q)
{
    if (IsEmpty(Q))
    {
        printf("queue is empty.
");
        return;
    }
    //         ,           
    QueueNode QNode = Q->Front->Next;
    while (QNode != NULL)
    {
        printf("%d
", QNode->Data);
        QNode = QNode->Next;
    }
}
int main()
{
    Queue Q;
    Q = CreateQueue(Q);
    for (int i = 1; i <= 2; i++)
    {
        Enqueue(i, Q);
    }
    PrintQueue(Q);
    FreeQueue(Q);
    PrintQueue(Q);
    return 0;
}