之前用习惯了面向对象的调用方式,用C写过程的还是有点不习惯,不过管用就行。
队列的操作很简单:
1、先进先出
2、入队的时候要检测队列是否已满;
3、出队列的时候要检测是否为空;
#include <iostream>
#include <memory>
#include "stdio.h"
#include "malloc.h"
typedef int ElementType;
#define CheckNULLQueue(Q) if ((Q) == NULL)\
printf("queue is null\n"); \
return
struct QueueRecord{
int Capacity;
int Size;
int Front;
int Rear;
ElementType* Array;
};
typedef QueueRecord* Queue;
bool IsEmpty(Queue Q){
if (NULL == Q){
return false;
}
return Q->Size == 0;
}
bool IsFull(Queue Q){
if (NULL == Q){
return false;
}
return Q->Size == Q->Capacity;
}
void MakeEmptyQueue(Queue Q){
if (NULL == Q){
return;
}
Q->Size = 0;
Q->Front = 1;
Q->Rear = 0;
}
Queue CreateQueue(int maxElements){
if (maxElements < 0){
printf("error\n");
return NULL;
}
Queue q = (Queue)malloc(sizeof(QueueRecord));
if (NULL == q){
printf("malloc error\n");
return NULL;
}
q->Capacity = maxElements;
MakeEmptyQueue(q);
q->Array = (ElementType*)malloc(maxElements * sizeof(ElementType));
if (q->Array == NULL){
printf("error\n");
free(q);
return NULL;
}
return q;
}
void Enqueue(ElementType X, Queue Q){
if (Q == NULL){
printf("Q is null\n");
return;
}
if (IsFull(Q)){
printf("Q is full with enqueue element:%d\n", X);
return;
}
++Q->Size;
Q->Rear = (Q->Rear + 1) % Q->Capacity;
Q->Array[Q->Rear] = X;
}
ElementType Front(Queue Q){
if (IsEmpty(Q)){
printf("Front error\n");
return -1;
}
return Q->Array[Q->Front];
}
void Dequeue(Queue Q){
if (IsEmpty(Q)){
printf("Dequeue is empty\n");
return ;
}
--Q->Size;
Q->Front = (Q->Front + 1) % Q->Capacity;
}
ElementType FrontAndDequeue(Queue Q){
if (IsEmpty(Q)){
printf("FrontAndDequeue error with queue is empty\n");
return -1;
}
ElementType res = Q->Array[Q->Front];
--Q->Size;
Q->Front = (Q->Front + 1) % Q->Capacity;
return res;
}
int main(){
int num = 3;
Queue pQueue = CreateQueue(num);
if (NULL == pQueue){
printf("CreateQueue failed\n");
return 0;
}
Dequeue(pQueue);
Enqueue(1, pQueue);
Enqueue(2, pQueue);
Enqueue(3, pQueue);
Enqueue(4, pQueue);
printf("front:%d\n", FrontAndDequeue(pQueue));
Dequeue(pQueue);
Dequeue(pQueue);
Dequeue(pQueue);
Dequeue(pQueue);
Dequeue(pQueue);
printf("front:%d\n", Front(pQueue));
}