编写程序实现循环队列的初始化,判断队列是否为空,入队列和出队列
时间: 2023-05-31 22:02:12 浏览: 139
循环队列是一种特殊的队列,它可以在一定程度上避免队列的溢出问题。下面是实现循环队列的基本操作:
1.初始化队列:
```python
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.head = -1
self.tail = -1
```
2.判断队列是否为空:
```python
def is_empty(self):
return self.head == -1
```
3.入队列:
```python
def enqueue(self, item):
if (self.tail + 1) % self.capacity == self.head:
print("Queue is full.")
return
elif self.is_empty():
self.head = 0
self.tail = 0
self.queue[self.tail] = item
else:
self.tail = (self.tail + 1) % self.capacity
self.queue[self.tail] = item
```
4.出队列:
```python
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
return None
elif self.head == self.tail:
item = self.queue[self.head]
self.head = -1
self.tail = -1
return item
else:
item = self.queue[self.head]
self.head = (self.head + 1) % self.capacity
return item
```
完整代码如下:
```python
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.head = -1
self.tail = -1
def is_empty(self):
return self.head == -1
def enqueue(self, item):
if (self.tail + 1) % self.capacity == self.head:
print("Queue is full.")
return
elif self.is_empty():
self.head = 0
self.tail = 0
self.queue[self.tail] = item
else:
self.tail = (self.tail + 1) % self.capacity
self.queue[self.tail] = item
def dequeue(self):
if self.is_empty():
print("Queue is empty.")
return None
elif self.head == self.tail:
item = self.queue[self.head]
self.head = -1
self.tail = -1
return item
else:
item = self.queue[self.head]
self.head = (self.head + 1) % self.capacity
return item
```
使用示例:
```python
q = CircularQueue(5)
print(q.is_empty()) # True
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.enqueue(6) # "Queue is full."
print(q.dequeue()) # 1
print(q.dequeue()) # 2
q.enqueue(6)
q.enqueue(7) # "Queue is full."
print(q.dequeue()) # 3
print(q.dequeue()) # 4
print(q.dequeue()) # 5
print(q.dequeue()) # 6
print(q.is_empty()) # True
```
阅读全文