重点思想:
- 当在线性表中插入一个元素时,插入位置的所有元素都后移一位
- 考虑因素:
- 线性表是否是满线性表
- 线性表插入位置是否可行
1 class linearlist_insert_elem(): 2 def __init__(self, data, maxsize): 3 self.data = data 4 self.maxsize = maxsize 5 self.length = len(data) 6 def list_insert(self, i, e): 7 if self.length == self.maxsize: 8 print("线性表%s已满,无法插入元素" % (self.data)) 9 # return -1 10 if i < 1 or i > self.length: 11 print("无法在位置%s插入元素" % i) 12 # return 0 13 else: 14 #在线性表队尾追加一个元素0 15 self.data.append(0) 16 for i in range(self.length, i, -1): 17 self.data[i] = self.data[i - 1] 18 self.data[i] = e 19 self.length += 1 20 print("在位置%s插入元素%s成功"%(i,e)) 21 return self.data 22 if __name__ == ‘__main__‘: 23 ob = linearlist_insert_elem([1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14], 20) 24 print(ob.data) 25 print(ob.length) 26 ob.list_insert(20, 17) 27 print(ob.data) 28 ob.list_insert(6, 17) 29 print(ob.data)
原文地址:https://www.cnblogs.com/carol-main-blog/p/11517361.html
时间: 2024-12-14 10:30:04