实现队列的①创建、②入队、③出队、④取队首元素、⑤判断队列是否为空 队列中的元素可以是学号与姓名 编写程序主函数,对各个功能函数进行调用 物理存储结构不限,顺序存储或者链式存储均可
时间: 2024-05-09 16:19:05 浏览: 27
队列的创建,销毁,清空,入队,出队,判空,判满等操作
链式存储实现队列:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, data):
node = Node(data)
if self.rear is None:
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
def dequeue(self):
if self.front is None:
return None
data = self.front.data
if self.front == self.rear:
self.front = None
self.rear = None
else:
self.front = self.front.next
return data
def get_front(self):
if self.front is None:
return None
return self.front.data
if __name__ == '__main__':
q = Queue()
q.enqueue({'id': 1001, 'name': 'Alice'})
q.enqueue({'id': 1002, 'name': 'Bob'})
q.enqueue({'id': 1003, 'name': 'Charlie'})
print(q.get_front()) # {'id': 1001, 'name': 'Alice'}
print(q.dequeue()) # {'id': 1001, 'name': 'Alice'}
print(q.is_empty()) # False
print(q.dequeue()) # {'id': 1002, 'name': 'Bob'}
print(q.dequeue()) # {'id': 1003, 'name': 'Charlie'}
print(q.is_empty()) # True
```
顺序存储实现队列:
```python
class Queue:
def __init__(self, capacity=10):
self.front = 0
self.rear = 0
self.size = 0
self.capacity = capacity
self.data = [None] * capacity
def is_empty(self):
return self.size == 0
def is_full(self):
return self.size == self.capacity
def enqueue(self, data):
if self.is_full():
return False
self.data[self.rear] = data
self.rear = (self.rear + 1) % self.capacity
self.size += 1
return True
def dequeue(self):
if self.is_empty():
return None
data = self.data[self.front]
self.front = (self.front + 1) % self.capacity
self.size -= 1
return data
def get_front(self):
if self.is_empty():
return None
return self.data[self.front]
if __name__ == '__main__':
q = Queue()
q.enqueue({'id': 1001, 'name': 'Alice'})
q.enqueue({'id': 1002, 'name': 'Bob'})
q.enqueue({'id': 1003, 'name': 'Charlie'})
print(q.get_front()) # {'id': 1001, 'name': 'Alice'}
print(q.dequeue()) # {'id': 1001, 'name': 'Alice'}
print(q.is_empty()) # False
print(q.dequeue()) # {'id': 1002, 'name': 'Bob'}
print(q.dequeue()) # {'id': 1003, 'name': 'Charlie'}
print(q.is_empty()) # True
```
阅读全文