数组如何实现队列?我们可以定义队列结构,成员有一维数组,一个记录队列头元素位置front,一个记录队列尾元素位置rear组成。
队列结构具体定义:
|
1 2 3 4 5 6 7 |
typedef int Position; struct QNode { ElementType *Data; /* 存储元素的数组 */ Position Front, Rear; /* 队列的头、尾指针 */ int MaxSize; /* 队列最大容量 */ }; typedef struct QNode *Queue; |
- 创建队列
|
1 2 3 4 5 6 7 8 |
Queue CreatQueue(int MaxSize) { Queue Q = (Queue)malloc(sizeof(QNode)); Q->Data = (ElementType*)malloc(MaxSize*sizeof(ElementType)); Q->Front = Q->Rear = 0; Q->MaxSize = MaxSize; return Q; } |
- 判断队列满
|
1 2 3 4 |
bool IsFull(Queue Q) { return ((Q->Rear+1)%Q->MaxSize == Q->Front); } |
- 入队操作
|
1 2 3 4 5 6 7 8 9 10 11 |
bool AddQ(Queue Q,ElementType X) { if (IsFull(Q)){ printf("队列满"); return false; }else{ Q->Rear = (Q->Rear+1)%Q->MaxSize; Q->Data[Q->Rear] = X; return true; } } |
- 判断队列空
|
1 2 3 4 |
bool IsEmpty(Queue Q) { return (Q->Front == Q->Rear); } |
- 出队操作
|
1 2 3 4 5 6 7 8 9 10 |
ElementType DeleteQ(Queue Q) { if (IsEmpty(Q)){ printf("队列空"); return false; }else{ Q->Front = (Q->Front+1)%Q->MaxSize; return Q->Data[Q->Front]; } } |