python 数据结构之顺序列表的实现

时间:2024-12-27 20:07:56

算法简要:

  追加直接往列表后面添加元素,插入是将插入位置后的元素全部往后面移动一个位置,然后再将这个元素放到指定的位置,将长度加1删除是将该位置后面的元素往前移动,

覆盖该元素,然后再将长度减1  

#!/usr/bin/python
# -*- coding: utf-8 -*- class SeqList(object):
def __init__(self,maxsize):
self.maxsize = maxsize
self.data = range(maxsize)
self.last = len(self.data) -1 def __getitem__(self, key):
if self.is_empty():
print 'seqlist is empty'
return
elif key<0 or key>self.last:
print 'the given key is Error'
return
else:
return self.data[key] def __setitem__(self, key, value):
if self.is_empty():
print 'seqlist is empty'
return
elif key<0 or key>self.last:
print 'the given key is Error'
return
else:
self.data[key] = value def __len__(self):
length = self.last + 1
return length def getlength(self):
return self.last+1 def clear(self):
self.data = [] def is_empty(self): if self.last == -1:
return True
else:
return False def is_full(self):
if self.last == self.maxsize-1:
return True
else:
return False def getelem(self,index): if self.is_empty():
print 'seqlist is empty'
return
elif index<0 or index>self.last:
print 'position is error'
else:
return self.data[index] def getindex(self,elem): if self.is_empty():
print 'seqlst is empty'
return
else:
for i in range(self.last):
if self.data[i]==elem:
return i def append(self,elem):
if self.is_empty():
print 'seqlist is empty'
return
else:
self.last +=1
self.data = self.data + [elem] def insert(self,index,elem): if self.is_empty():
print 'seqlist is empty'
return
elif index<0 or index> self.last+1:
print 'postion is error'
return
elif index == self.last+1:
self.last+=1
self.data = self.data + [elem]
else:
self.data += [elem]
if index ==0:
for i in self.data[self.last::-1]:
self.data[i+1] = self.data[i]
else:
for i in self.data[self.last:index-1:-1]:
self.data[i+1] = self.data[i]
self.data[index] = elem
self.last+=1 #print self.data def delete(self,index): if self.is_empty():
print 'seqlist is empty'
return
elif index<0 or index> self.last+1:
print 'postion is error'
return
elif index == self.last+1:
self.last -= 1
self.data =self.data[:-1]
else: for i in self.data[:-1]:
if i >= index:
self.data[i] = self.data[i+1]
else:
pass
self.data = self.data[:-1]
self.last -= 1 sl = SeqList(5) print sl.data sl.append(5) print sl.data sl.insert(6,10) print sl.data sl.delete(5) print sl.data
  

说明:其实python中得list 本身是支持该种数据结构的,可以直接使用。