代码:
class Student:
def __init__(self,capacity = 10):
self.capacity = capacity #线性表的最大容量
self.size = 0 #已存储的元素个数
self.data = [None]*capacity
# 判满
def is_full(self):
if self.capacity == self.size:
print("顺序表已满")
# 判空
def is_empty(self):
if self.size == 0:
print("顺序表为空")
# 尾插
def add_tail(self,name,age,grade):
if self.is_full():
print("顺序表已满,插入失败")
return False
else:
self.data[self.size] = [name,age,grade]
self.size += 1
# 任意位置插入
def add_idex(self,idex,name,age,grade):
# 判满,判断位置是否合理
if self.is_full() or idex < 0 or idex > self.size:
print("插入失败")
return False
else:
# 腾位
i = 0
while i < self.size - idex:
self.data[self.size - i] = self.data[self.size - i - 1]
i += 1
# 插入数据
self.data[idex] = [name,age,grade]
# 插入成功,顺序表长度自增
self.size +=1
#按位置删除
def del_idex(self,idex):
if self.is_empty() or idex < 0 or idex > self.size:
print("删除失败")
return False
else:
i = idex
while i < self.size - 1:
self.data[i] = self.data[i + 1]
i += 1
self.size -= 1
# 按位置修改
def rep_idex(self,idex,name,age,grade):
if self.is_empty() or idex < 0 or idex > self.size:
print("修改失败")
return False
else:
self.data[idex] = [name,age,grade]
# 查找返回下标
def find_idex(self,name,age,grade):
if self.is_empty():
print("查找失败")
return False
else:
for i in range(self.size):
if self.data[i] == [name,age,grade]:
return i
else:
return False
#去重
def de_wight(self):
if self.is_empty():
print("去重失败")
return False
i = 0
while i < self.size:
j = i+1
while j<self.size:
if self.data[i] == self.data[j]:
self.del_idex(j)
j -= 1
j += 1
i += 1
# 展示
def show(self):
if self.is_empty():
print("顺序表为空")
return
else:
i = 0
while i < self.size:
print(self.data[i])
i += 1
print()
if __name__ == '__main__':
a = Student(5)
#尾插
a.add_tail('张三', 18, 87)
a.add_tail('李四', 20, 76)
a.add_tail('王五', 19, 66)
a.add_tail('赵六', 30, 100)
a.show()
#任意位置插入
a.add_idex(0,'张三', 18, 87)
a.show()
# 按位置修改
a.rep_idex(2,'王五', 19, 66)
a.show()
# 查找返回下标
print(a.find_idex('王五', 19, 66))
print()
# 去重
a.de_wight()
a.show()
结果:
