基于循环队列或链队列,实现队列的各种基本运算,并在此基础上设计一个主程序完成如下功能:(1)将一组整数加入队列。(2)打印队列的所有元素。(3)将其中若干元素出队并打印出队的元素。(4)打印队列剩余的元素。
时间: 2024-11-12 10:34:06 浏览: 31
为了实现基于循环队列或链队列的队列的基本运算,我们可以分别构建两个类,一个是`CircularQueue`(基于数组),另一个是`LinkedListQueue`(基于链表)。这里给出一个简单的实现例子:
```python
# 基于循环队列的实现
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = -1
self.rear = -1
# 入队
def enqueue(self, value):
if self.is_full():
print("Queue is full.")
return
if self.isEmpty():
self.front = 0
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = value
# 出队
def dequeue(self):
if self.isEmpty():
print("Queue is empty.")
return None
value = self.queue[self.front]
if self.front == self.rear:
self.front = -1
self.rear = -1
else:
self.front = (self.front + 1) % self.capacity
return value
# 判断队列是否为空
def isEmpty(self):
return self.front == -1
# 判断队列是否已满
def is_full(self):
return (self.rear + 1) % self.capacity == self.front
# 基于链队列的实现(简化版本)
class LinkedListQueue:
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def __init__(self):
self.head = None
self.tail = None
# ...类似上面的 enqueue, dequeue, isEmpty 和 isFull 方法 ...
# 主程序
def main():
size = int(input("Enter the size of the queue: "))
choice = input("Choose a queue type (1 for circular, 2 for linked list): ")
if choice == '1':
queue = CircularQueue(size)
elif choice == '2':
queue = LinkedListQueue()
else:
print("Invalid choice.")
numbers = list(map(int, input("Enter a list of integers to add to the queue: ").split()))
for num in numbers:
queue.enqueue(num)
print("Elements in the queue:")
while not queue.isEmpty():
print(queue.dequeue(), end=" ")
if not queue.isEmpty():
print("\nRemaining elements after dequeuing:")
while not queue.isEmpty():
print(queue.dequeue(), end=" ")
if __name__ == "__main__":
main()
```
在这个主程序中,用户可以选择循环队列或链队列,然后输入一组整数添加到队列。接着,程序会打印所有队列元素,然后让用户选择几个元素出队并再次打印队列。最后,无论是否还有剩余元素,都会打印剩余的元素。
阅读全文