学生表抽象成一个队列,每个学生(包括姓名、学号、成绩)作为队列中的一个元素,该队列采用顺序存储结构,对该队列进行初始化、输出、入队和出队基本操作,
时间: 2024-05-05 13:15:29 浏览: 48
队列的应用-数据结构课件 计算机
并实现以下功能:
1. 查询某个学生的信息;
2. 查询成绩最高和最低的学生信息;
3. 查询平均成绩。
以下是Python代码实现:
```python
class Student:
def __init__(self, name, id, score):
self.name = name
self.id = id
self.score = score
class StudentQueue:
def __init__(self, size):
self.size = size
self.queue = [None] * size
self.front = 0
self.rear = 0
def is_empty(self):
return self.front == self.rear
def is_full(self):
return (self.rear + 1) % self.size == self.front
def enqueue(self, student):
if self.is_full():
print("Queue is full")
else:
self.queue[self.rear] = student
self.rear = (self.rear + 1) % self.size
def dequeue(self):
if self.is_empty():
print("Queue is empty")
else:
student = self.queue[self.front]
self.front = (self.front + 1) % self.size
return student
def output(self):
for i in range(self.front, self.rear):
print("Name: {}, ID: {}, Score: {}".format(self.queue[i].name, self.queue[i].id, self.queue[i].score))
def get_student_info(self, id):
for i in range(self.front, self.rear):
if self.queue[i].id == id:
print("Name: {}, ID: {}, Score: {}".format(self.queue[i].name, self.queue[i].id, self.queue[i].score))
return
print("Student not found")
def get_highest_score(self):
highest_score = -1
highest_student = None
for i in range(self.front, self.rear):
if self.queue[i].score > highest_score:
highest_score = self.queue[i].score
highest_student = self.queue[i]
print("Name: {}, ID: {}, Score: {}".format(highest_student.name, highest_student.id, highest_student.score))
def get_lowest_score(self):
lowest_score = 101
lowest_student = None
for i in range(self.front, self.rear):
if self.queue[i].score < lowest_score:
lowest_score = self.queue[i].score
lowest_student = self.queue[i]
print("Name: {}, ID: {}, Score: {}".format(lowest_student.name, lowest_student.id, lowest_student.score))
def get_average_score(self):
total_score = 0
count = 0
for i in range(self.front, self.rear):
total_score += self.queue[i].score
count += 1
if count == 0:
print("No student in the queue")
else:
print("Average score: {}".format(total_score / count))
# 测试代码
queue = StudentQueue(10)
queue.enqueue(Student("Tom", "001", 85))
queue.enqueue(Student("Jerry", "002", 90))
queue.enqueue(Student("Alice", "003", 95))
queue.enqueue(Student("Bob", "004", 80))
queue.output() # 输出所有学生信息
queue.get_student_info("002") # 查询学号为002的学生信息
queue.get_highest_score() # 查询成绩最高的学生信息
queue.get_lowest_score() # 查询成绩最低的学生信息
queue.get_average_score() # 查询平均成绩
queue.enqueue(Student("David", "005", 70))
queue.enqueue(Student("Grace", "006", 75))
queue.output() # 输出所有学生信息
queue.dequeue()
queue.dequeue()
queue.output() # 输出所有学生信息
```
阅读全文