队列
数组实现
//检验是否为空
int IsEmpty(Queue Q)
{
return Q->Size == 0;
}
//检验是否满了
int IsFull(Queue Q)
{
return Q->Size == Q->Capacity - 1;
}
//创建一个队列
Queue CreateQueue(int Maxelements)
{
Queue Q = malloc(sizeof(struct QueueRecord_Array));
Q->Array = malloc(sizeof(int)*Maxelements);
if(Q->Array == NULL)
{
printf("Out of Space\n");
exit(EXIT_FAILURE);
}
Q->Capacity = Maxelements;
Q->Size = 0;
Q->Front = 0;
Q->Rear = 0;
return Q;
}
//销毁一个队列
void DisposeQueue(Queue Q)
{
free(Q->Array);
free(Q);
}
//置空一个队列
void MakeEmpty(Queue Q)
{
Q->Size = 0;
Q->Front = 0;
Q->Rear = 0;
}
//入队
void Enqueue(int X, Queue Q)
{
if(IsFull(Q))
{
printf("Queue is Full\n");
exit(EXIT_FAILURE);
}
Q->Size++;
Q->Array[Q->Rear] = X;
Q->Rear = (++Q->Rear) % Q->Capacity; //实现回环
}
//检查队首元素
int Front(Queue Q)
{
return Q->Array[Q->Front];
}
//出队
int Dequeue(Queue Q)
{
int AnswerCell;
if(IsEmpty(Q))
{
printf("Queue is Empty\n");
exit(EXIT_FAILURE);
}
Q->Size--;
AnswerCell = Q->Array[Q->Front];
Q->Front = (++Q->Front) % Q->Capacity;
return AnswerCell;
}
//检查队首然后出队
//返回的是队首的值
int FrontandDequeue(Queue Q)
{
Dequeue(Q);
return Front(Q);
}
typedef struct QueueRecord_Array* Queue;
struct QueueRecord_Array
{
int Capacity;
int Front;
int Rear;
int Size;
int *Array;
};
链表实现
然而队列的链表实现就比较简单了,这里就只写出结构体,操作就不重复提了。
typedef struct QueueRecord_List* List;
struct QueueRecord_List
{
List _front;
List _rear;
int Size;
};
struct Member
{
int num;
List Next;
};