数组结构有几种队列的分类?python
时间: 2024-02-03 14:15:35 浏览: 24
数组结构可以分为两种队列分类:顺序队列和循环队列。
顺序队列:顺序队列就是用数组来实现的队列,队列的头在数组的0号位置,队列的尾在数组的末尾位置。当队列满时,就不能继续插入,当队列为空时,就不能继续弹出。
循环队列:循环队列也是用数组来实现的队列,队列的头和尾都可以在数组中任意位置。当队列满时,队列的头和尾相邻,当队列为空时,队列的头和尾也相邻。
以下是 Python 语言实现顺序队列和循环队列的示例代码:
```python
# 顺序队列的实现
class SeqQueue:
def __init__(self, capacity: int):
self.capacity = capacity
self.queue = [None] * capacity
self.head = 0
self.tail = 0
def is_empty(self) -> bool:
return self.head == self.tail
def is_full(self) -> bool:
return (self.tail + 1) % self.capacity == self.head
def enqueue(self, item: Any) -> bool:
if self.is_full():
return False
self.queue[self.tail] = item
self.tail = (self.tail + 1) % self.capacity
return True
def dequeue(self) -> Optional[Any]:
if self.is_empty():
return None
item = self.queue[self.head]
self.head = (self.head + 1) % self.capacity
return item
# 循环队列的实现
class CircularQueue:
def __init__(self, capacity: int):
self.capacity = capacity + 1
self.queue = [None] * self.capacity
self.head = 0
self.tail = 0
def is_empty(self) -> bool:
return self.head == self.tail
def is_full(self) -> bool:
return (self.tail + 1) % self.capacity == self.head
def enqueue(self, item: Any) -> bool:
if self.is_full():
return False
self.queue[self.tail] = item
self.tail = (self.tail + 1) % self.capacity
return True
def dequeue(self) -> Optional[Any]:
if self.is_empty():
return None
item = self.queue[self.head]
self.head = (self.head + 1) % self.capacity
return item
```