写一个代码分别实现环形队列、链队的各种基本运算;其次设计程序调用环形队列、链队的这些算法进行功能测试
时间: 2024-12-12 20:18:57 浏览: 17
环形队列和链队是数据结构中常用的线性队列实现方式,这里我会简要地给出它们的基本操作,并提供一些简单的伪代码示例。
**环形队列(Circular Queue)实现:**
```python
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = -1
self.rear = -1
# 入队(Enqueue)
def enqueue(self, item):
if (self.rear + 1) % self.capacity == self.front:
print("Queue is full")
else:
if self.rear == -1:
self.front = 0
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = item
# 出队(Dequeue)
def dequeue(self):
if self.isEmpty():
print("Queue is empty")
else:
item = self.queue[self.front]
if self.front == self.rear:
self.front = self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
return item
# 查看队头元素
def peek(self):
if self.isEmpty():
print("Queue is empty")
else:
return self.queue[self.front]
# 判断队列是否为空
def isEmpty(self):
return self.front == -1 and self.rear == -1
```
**链式队列(Linked Queue)实现:**
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedListQueue:
def __init__(self):
self.head = None
self.tail = None
# 入队
def enqueue(self, item):
new_node = Node(item)
if not self.head:
self.head = self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
# 出队
def dequeue(self):
if not self.head:
print("Queue is empty")
else:
temp = self.head
self.head = self.head.next
if self.head is None:
self.tail = None
return temp.data
# 查看队头
def peek(self):
if not self.head:
print("Queue is empty")
else:
return self.head.data
# 判断队列是否为空
def isEmpty(self):
return not self.head
```
为了测试这两个队列的功能,你可以编写如下程序:
```python
# 初始化队列并添加元素
cq = CircularQueue(5)
lq = LinkedListQueue()
cq.enqueue(1)
cq.enqueue(2)
lq.enqueue(3)
# 打印队头元素并出队
print("Circular Queue front:", cq.peek())
cq.dequeue()
print("Circular Queue after dequeue:", cq.peek())
print("\nLinkedList Queue front:", lq.peek())
lq.dequeue()
print("LinkedList Queue after dequeue:", lq.peek())
# 检查队列是否空
print("Is Circular Queue empty?", cq.isEmpty())
print("Is LinkedList Queue empty?", lq.isEmpty())
```
阅读全文