#!/usr/bin/env python #-*- coding:utf-8 -*- #顺序表 Sequence List class SqList(): def __init__(self,size): self.data = [None for i in range(size)]#Python中没有类似C语言的那种直接创建空数组的方式,间接使用 self.maxsize = size self.length = 0
#判断顺序表是否为空 def is_empty(self): return self.length==0
#判断顺序表是否满 def is_full(self): return self.length==self.maxsize
#求顺序表的长度 def get_length(self): return self.length
#取顺序表的数据 def get_elem(self, i): if self.is_empty(): raise IndexError('SqList is empty') elif i > self.length or i < 0: raise IndexError('not correct position') else: return self.data[i-1]
#根据数据元素值求位置,没有找到返回-1 def locate(self, e): i = 0 while(i<self.length and self.data[i]!=e): i+=1 if i <self.length -1: return i+1 else: return -1 #插入元素,i为第几个位置 def insert(self, i, e): if not self.is_full(): if i>0 and i<=self.length+1: for index in range(self.length-1,i-2,-1):#不包含尾部 self.data[index+1]=self.data[index] self.data[i-1]= e self.length +=1 print("-------------") else: raise IndexError('SqList is full.') def delete(self,i):#本程序i指的是插入的序号 if not self.is_empty(): if i<1 and i>self.length: raise IndexError('not correct position') deelem = self.get_elem(i) for index in range(i-1,self.length-1): self.data[index]= self.data[index+1] self.data[self.length-1]=None #很有必要的操作 self.length -= 1 return deelem if __name__ == '__main__': s = SqList(5) for i in range(0,3): s.insert(i+1,i) print(s.data) print(s.delete(2)) print(s.data)