(1)输入1-10的数字组成普通线性队列; (2)判断此时队列的队首元素; (3)打印出队列操作后的队首元素; (4)由于普通线性队列的限制,此时尝试使用循环队列来解决上述问题
时间: 2024-11-22 22:43:32 浏览: 14
首先,我们假设你正在使用Python编写程序,这里是一个简单的例子:
1. **输入1-10的数字组成普通线性队列**:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
def enqueue(queue, data):
new_node = Node(data)
if queue is None or queue.front is None:
queue.front = new_node
else:
current = queue.front
while current.next is not None:
current = current.next
current.next = new_node
# 示例:输入1到10
for i in range(1, 11):
enqueue(queue, i)
```
2. **判断队列的队首元素**:
```python
def dequeue(queue):
if queue is None or queue.front is None:
return None
front_data = queue.front.data
queue.front = queue.front.next
return front_data
queue_front = dequeue(queue)
```
3. **打印出队首元素**:
```python
if queue_front is not None:
print("队首元素:", queue_front)
else:
print("队列为空")
```
4. **转换为循环队列**:
对于循环队列,我们需要跟踪当前的`rear`指针,并当`enqueue`满时将`front`移动到`rear`。这里是循环队列版本的示例:
```python
class CircularQueue:
def __init__(self, size=10):
self.size = size
self.queue = [None] * size
self.rear = -1
self.front = -1
# ... (其余enqueue、dequeue方法需要修改以考虑环形结构)
# 使用循环队列
cq = CircularQueue()
# ... (继续之前的插入操作并调整判断队首元素的方法)
```
阅读全文