一、线性表类的定义
class Sqlist:
capacity=0
size=0
newcapacity=0
def __init__(self):
self.initcapacity=5;
self.capacity=self.initcapacity
self.data=[None]*self.capacity
self.size=0
def resize(self,newcapacity):
assert newcapacity>=0
olddata=self.data
self.data=[None]*self.newcapacity
self.capacity=newcapacity
for i in range(self.size):
self.data[i]=olddata[i]
def CreateList(self,a):
for i in range(0,len(a)):
if self.size==self.capacity:
self.resize(2*self.size);
self.data[self.size]=a[i]
self.size+=1
def Add(self,e):
if self.size==self.capacity:
self.resize(2*self.size)
self.data[self.size]=e
self.size+=1
def getsize(self):
return self.size
def __getitem__(self,i):
assert 0<=i<self.size
return self.data[i]
def __setitem__(self,i,x):
assert 0<=i<self.size
self.data[i]=x
def GetNo(self,e):
i=0;
while i<self.size and self.data[i]!=e:
i+=1
if(i>self.size):
return -1;
else:
return i;
def Insert(self,i,e):
assert 0<=i<=self.size
if self.size==self.capacity:
self.resize(2*self.size)
for j in range(self.size,i-1,-1):
self.data[j]=self.data[j-1]
self.data[i]=e
self.size+=1
def Delete(self,i):
assert 0<=i<=self.size-1
for j in range(i,self.size-1):
self.data[j]=self.data[j+1]
self.size-=1
if self.capacity>self.initcapacity and self.size<=self.capacity/4:
self.resize(self.capacity//2)
def display(self):
for i in range(self.size):
print(self.data[i],end=' ')
print()
二、线性表类的测试代码
if __name__=='__main__':
L=Sqlist()
for i in range(1,6) :
L.Add(i)
print ("L: ",end=' '),L.display()
print("序号为2的元素=%d"%(L[2]))
print("设置序号为2的元素为8")
L[2]=8
print("序号为2的元素=%d" %(L[2]))
n=L.getsize()
print ("size=%d" %(n))
for i in range(0,n):
print("删除%d序号的元素"%(0))
L.Delete(0)
print("L:",end=" "),L.display()
print ("size=%d" %(L.getsize ()))