使用顺序队列实现上述数据进队和出队的操作,每次进队和出队操作后需要遍历队列。 二、使用链式队列实现上述数据进队和出队的操作,每次进队和出队操作后需要遍历队列。 三、使用循环队列实现上述数据进队和出队的操作,每次进队和出队操作后需要遍历队列。
时间: 2024-02-03 22:12:24 浏览: 70
一、使用顺序队列实现数据进队和出队的操作,每次操作后遍历队列:
```python
class SeqQueue:
def __init__(self, capacity):
self.capacity = capacity
self.front = 0
self.rear = 0
self.data = [None] * capacity
def is_empty(self):
return self.front == self.rear
def is_full(self):
return (self.rear + 1) % self.capacity == self.front
def enqueue(self, value):
if self.is_full():
print("队列已满")
return False
self.data[self.rear] = value
self.rear = (self.rear + 1) % self.capacity
return True
def dequeue(self):
if self.is_empty():
print("队列已空")
return None
value = self.data[self.front]
self.front = (self.front + 1) % self.capacity
return value
def traverse(self):
i = self.front
while i != self.rear:
print(self.data[i], end=" ")
i = (i + 1) % self.capacity
print()
```
二、使用链式队列实现数据进队和出队的操作,每次操作后遍历队列:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkQueue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, value):
node = Node(value)
if self.rear is None:
self.front = node
else:
self.rear.next = node
self.rear = node
def dequeue(self):
if self.is_empty():
print("队列已空")
return None
value = self.front.value
self.front = self.front.next
if self.front is None:
self.rear = None
return value
def traverse(self):
node = self.front
while node is not None:
print(node.value, end=" ")
node = node.next
print()
```
三、使用循环队列实现数据进队和出队的操作,每次操作后遍历队列:
```python
class CirQueue:
def __init__(self, capacity):
self.capacity = capacity
self.front = 0
self.rear = 0
self.data = [None] * capacity
def is_empty(self):
return self.front == self.rear
def is_full(self):
return (self.rear + 1) % self.capacity == self.front
def enqueue(self, value):
if self.is_full():
print("队列已满")
return False
self.data[self.rear] = value
self.rear = (self.rear + 1) % self.capacity
return True
def dequeue(self):
if self.is_empty():
print("队列已空")
return None
value = self.data[self.front]
self.front = (self.front + 1) % self.capacity
return value
def traverse(self):
i = self.front
while i != self.rear:
print(self.data[i], end=" ")
i = (i + 1) % self.capacity
print()
```
以上三种队列实现方式,每次操作后都需要遍历队列,这样会增加时间复杂度。如果只需要查看队头元素,可以在队列中添加一个变量来记录队头元素。
阅读全文