求循环队列的长度的代码
时间: 2024-04-30 08:22:32 浏览: 25
循环队列的长度可以通过以下代码实现:
```python
class CircularQueue:
def __init__(self, k: int):
self.queue = [None] * k
self.maxsize = k
self.front = 0
self.rear = 0
self.length = 0
def size(self) -> int:
return self.length
```
其中,`size()`方法返回队列当前的长度,即元素个数。
相关问题
循环队列求队列长度代码
循环队列是一种使用固定大小的数组实现的队列,可以循环利用数组中的空间。求队列长度的代码如下:
```c
#define MAX_SIZE 100
typedef struct {
int front; // 队头指针
int rear; // 队尾指针
int size; // 队列长度
int data[MAX_SIZE]; // 存放队列元素的数组
} CircularQueue;
// 初始化队列
void initQueue(CircularQueue *queue) {
queue->front = 0;
queue->rear = 0;
queue->size = 0;
}
// 判断队列是否为空
int isEmpty(CircularQueue *queue) {
return queue->size == 0;
}
// 判断队列是否已满
int isFull(CircularQueue *queue) {
return queue->size == MAX_SIZE;
}
// 入队
void enqueue(CircularQueue *queue, int element) {
if (isFull(queue)) {
printf("Queue is full. Cannot enqueue.\n");
return;
}
queue->data[queue->rear] = element;
queue->rear = (queue->rear + 1) % MAX_SIZE; // 循环更新队尾指针
queue->size++;
}
// 出队
int dequeue(CircularQueue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty. Cannot dequeue.\n");
return -1;
}
int element = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE; // 循环更新队头指针
queue->size--;
return element;
}
// 求队列长度
int getQueueLength(CircularQueue *queue) {
return queue->size;
}
```
上述代码中,使用`CircularQueue`结构体表示循环队列,其中`front`和`rear`分别指向队头和队尾元素,`size`表示队列的长度,`data`数组存放队列元素。`initQueue`用于初始化队列,`isEmpty`和`isFull`判断队列是否为空或已满,`enqueue`和`dequeue`分别进行入队和出队操作,`getQueueLength`用于求队列长度。
c语言代码求循环队列长度
Sure, I can help you with that. Here's an example of C language code to find the length of a circular queue:
int front, rear, count;
int cq[5];
void cq_length() {
if(front == -1 && rear == -1) {
printf("\nCircular Queue is Empty.");
}
else {
count = (rear+5-front) % 5 + 1; //calculating length of circular queue
printf("\nLength of Circular Queue: %d", count);
}
}
In this code, we are initializing front, rear, and count as integers and cq as an array. Then, we define a function cq_length() to find the length of the circular queue. Finally, we calculate the length using a formula and print the output.
Hope this helps! Let me know if you have any more questions.
阅读全文