写出学生数据元素(学号1,2,3…10,姓名) 10个 对数据元素进行查找、删除5、插入5 分别采用顺序和链式进行存储的算法
时间: 2024-09-15 21:11:33 浏览: 33
学生信息管理系统数据结构课程设计
5星 · 资源好评率100%
首先,我们分别介绍顺序存储(数组)和链式存储(链表)的数据结构。
**顺序存储(数组):**
假设我们使用整数表示学号,字符串表示姓名,我们可以创建一个长度为10的数组:
```python
# 示例代码 (Python)
class StudentArray:
def __init__(self):
self.students = [None] * 10
# 插入操作 (顺序查找索引)
def insert(self, student_id, name):
for i in range(len(self.students)):
if self.students[i] is None:
self.students[i] = {"id": student_id, "name": name}
break
else:
print("数组已满,无法插入新的学生.")
# 查找操作
def find(self, student_id):
for i, student in enumerate(self.students):
if student and student["id"] == student_id:
return student["name"]
return "未找到该学生."
# 删除操作
def delete(self, student_id):
for i in range(len(self.students)):
if self.students[i] and self.students[i]["id"] == student_id:
self.students[i] = None
break
else:
print("未找到该学生.")
# 删除第5个位置的学生 (直接删除指定位置的内容)
def delete_at_index(self, index):
if index >= 0 and index < len(self.students):
self.students[index] = None
else:
print("无效的索引.")
```
**链式存储(链表):**
对于链表,每个节点包含一个学生信息和指向下一个节点的指针:
```python
class Node:
def __init__(self, id, name):
self.id = id
self.name = name
self.next = None
class LinkedListStudent:
def __init__(self):
self.head = None
# 插入操作
def insert(self, student_id, name):
new_node = Node(student_id, name)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 查找操作
def find(self, student_id):
current = self.head
while current:
if current.id == student_id:
return current.name
current = current.next
return "未找到该学生."
# 删除操作
def delete(self, student_id):
current = self.head
previous = None
while current:
if current.id == student_id:
if previous:
previous.next = current.next
else:
self.head = current.next
break
previous = current
current = current.next
# 删除第5个学生 (需遍历并计数节点)
def delete_at_index(self, index):
if index >= 0:
count = 0
current = self.head
while current and count < index:
count += 1
current = current.next
if current:
if count > 0:
current = current.next
else:
raise IndexError("无效的索引.")
else:
raise IndexError("无效的索引.")
```
相关问题--
1. 顺序存储和链式存储相比,哪种更适合频繁的插入和删除操作?
2. 如何优化链式存储的删除操作,使之更高效?
3. 顺序查找和链式查找的时间复杂度各是多少?
阅读全文