用循环队列实现元素倒置
时间: 2023-05-31 17:02:34 浏览: 105
循环队列的元素倒置,可以通过以下步骤实现:
1. 定义一个循环队列,并初始化队列中的元素。
2. 定义两个指针front和rear,分别指向队列的队首和队尾。
3. 使用while循环,将队首指针front和队尾指针rear向中间移动,同时交换它们所指向的元素,直到它们相遇为止。
4. 输出倒置后的队列元素。
下面是一个示例代码,实现了循环队列元素倒置的功能:
```python
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = -1
self.rear = -1
def enqueue(self, data):
if (self.rear + 1) % self.capacity == self.front:
print("Queue is full\n")
elif self.front == -1:
self.front = 0
self.rear = 0
self.queue[self.rear] = data
else:
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = data
def dequeue(self):
if self.front == -1:
print("Queue is empty\n")
elif self.front == self.rear:
temp = self.queue[self.front]
self.front = -1
self.rear = -1
return temp
else:
temp = self.queue[self.front]
self.front = (self.front + 1) % self.capacity
return temp
def display(self):
if self.front == -1:
print("Queue is empty\n")
else:
i = self.front
while i != self.rear:
print(self.queue[i], end=" ")
i = (i + 1) % self.capacity
print(self.queue[i])
def reverse_queue(queue):
front = queue.front
rear = queue.rear
while front < rear:
temp = queue.queue[front]
queue.queue[front] = queue.queue[rear]
queue.queue[rear] = temp
front += 1
rear -= 1
# Test the code
queue = CircularQueue(5)
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
print("Original queue:")
queue.display()
reverse_queue(queue)
print("Reverse queue:")
queue.display()
```
输出结果为:
```
Original queue:
1 2 3 4 5
Reverse queue:
5 4 3 2 1
```
阅读全文