编写一个程序实现队列的各种基本运算. (1) 初始化循环队列 (2) 判断队列是否为空 (3) 判断队列是否为满 (4)入队操作 (5) 出队操作 (6) 取当前队头元素值返回
时间: 2024-05-16 19:15:36 浏览: 71
以下是 Python 代码实现:
```python
class CircularQueue:
def __init__(self, max_size):
self.max_size = max_size
self.queue = [None] * max_size
self.head = 0
self.tail = 0
def is_empty(self):
return self.head == self.tail
def is_full(self):
return (self.tail + 1) % self.max_size == self.head
def enqueue(self, data):
if self.is_full():
print("队列已满")
return False
self.queue[self.tail] = data
self.tail = (self.tail + 1) % self.max_size
return True
def dequeue(self):
if self.is_empty():
print("队列为空")
return None
data = self.queue[self.head]
self.queue[self.head] = None
self.head = (self.head + 1) % self.max_size
return data
def get_front(self):
if self.is_empty():
print("队列为空")
return None
return self.queue[self.head]
```
初始化循环队列:
```python
queue = CircularQueue(5)
```
判断队列是否为空:
```python
queue.is_empty()
```
判断队列是否为满:
```python
queue.is_full()
```
入队操作:
```python
queue.enqueue("A")
```
出队操作:
```python
queue.dequeue()
```
取当前队头元素值:
```python
queue.get_front()
```
阅读全文