顺序表python版的实现(部分功能未实现)
1 #!/usr/bin/env python
2 # -*- coding:utf-8 -*-
3
4 class SeqList(object): 5 def __init__(self, max=8): 6 self.max = max #创建默认为8
7 self.num = 0 8 self.date = [None] * self.max 9 #list()会默认创建八个元素大小的列表,num=0,并有链接关系
10 #用list实现list有些荒谬,全当练习
11 #self.last = len(self.date)
12 #当列表满时,扩建的方式省略
13 def is_empty(self): 14 return self.num is 0 15
16 def is_full(self): 17 return self.num is self.max 18
19 #获取某个位置的元素
20 def __getitem__(self, key): 21 if not isinstance(key, int): 22 raise TypeError 23 if 0<= key < self.num: 24 return self.date[key] 25 else: 26 #表为空或者索引超出范围都会引发索引错误
27 raise IndexError 28
29 #设置某个位置的元素
30 def __setitem__(self, key, value): 31 if not isinstance(key, int): 32 raise TypeError 33 #只能访问列表里已有的元素,self.num=0时,一个都不能访问,self.num=1时,只能访问0
34 if 0<= key < self.num: 35 self.date[key] = value #该位置无元素会发生错误
36 else: 37 raise IndexError 38
39 def clear(self): 40 self.__init__() 41
42 def count(self): 43 return self.num 44
45 def __len__(self): 46 return self.num 47
48 #加入元素的方法 append()和insert()
49 def append(self,value): 50 if self.is_full(): 51 #等下扩建列表
52 print("list is full") 53 return
54 else: 55 self.date[self.num] = value 56 self.num += 1
57
58 def insert(self,key,value): 59 if not isinstance(key, int): 60 raise TypeError 61 if key<0: #暂时不考虑负数索引
62 raise IndexError 63 #当key大于元素个数时,默认尾部插入
64 if key>=self.num: 65 self.append(value) 66 else: 67 #移动key后的元素
68 for i in range(self.num, key, -1): 69 self.date[i] = self.date[i-1] 70 #赋值
71 self.date[key] = value 72 self.num += 1
73
74 #删除元素的操作
75 def pop(self,key=-1): 76 if not isinstance(key, int): 77 raise TypeError 78 if self.num-1 < 0: 79 raise IndexError("pop from empty list") 80 elif key == -1: 81 #原来的数还在,但列表不识别他
82 self.num -= 1
83 else: 84 for i in range(key,self.num-1): 85 self.date[i] = self.date[i+1] 86 self.num -= 1
87
88 def index(self,value,start=0): 89 for i in range(start, self.num): 90 if self.date[i] == value: 91 return i 92 #没找到
93 raise ValueError("%d is not in the list" % value) 94
95 #列表反转
96 def reverse(self): 97 i,j = 0, self.num - 1
98 while i<j: 99 self.date[i], self.date[j] = self.date[j], self.date[i] 100 i,j = i+1, j-1
101
102 if __name__=="__main__": 103 a = SeqList() 104 print(a.date) 105 #num == 0
106 print(a.is_empty()) 107 a.append(0) 108 a.append(1) 109 a.append(2) 110 print(a.date) 111 print(a.num) 112 print(a.max) 113 a.insert(1,6) 114 print(a.date) 115 a[1] = 5
116 print(a.date) 117 print(a.count()) 118
119 print("返回值为2(第一次出现)的索引:", a.index(2, 1)) 120 print("====") 121 t = 1
122 if t: 123 a.pop(1) 124 print(a.date) 125 print(a.num) 126 else: 127 a.pop() 128 print(a.date) 129 print(a.num) 130 print("========") 131 print(len(a)) 132
133 a.reverse() 134 print(a.date) 135 """
136 print(a.is_full()) 137 a.clear() 138 print(a.date) 139 print(a.count()) 140 """