你能用Python写一个顺序表吗
时间: 2023-05-13 19:05:33 浏览: 90
当然可以,以下是一个简单的Python顺序表实现:
class SeqList:
def __init__(self, maxsize=None):
self.maxsize = maxsize
self.items = [None] * maxsize
self.length = 0
def __len__(self):
return self.length
def __getitem__(self, index):
if index < 0 or index >= self.length:
raise IndexError('Index out of range')
return self.items[index]
def __setitem__(self, index, value):
if index < 0 or index >= self.length:
raise IndexError('Index out of range')
self.items[index] = value
def __repr__(self):
return '<SeqList: {}>'.format(self.items[:self.length])
def insert(self, index, value):
if self.length >= self.maxsize:
raise Exception('SeqList is full')
if index < 0 or index > self.length:
raise IndexError('Index out of range')
for i in range(self.length, index, -1):
self.items[i] = self.items[i-1]
self.items[index] = value
self.length += 1
def delete(self, index):
if index < 0 or index >= self.length:
raise IndexError('Index out of range')
for i in range(index, self.length-1):
self.items[i] = self.items[i+1]
self.items[self.length-1] = None
self.length -= 1
阅读全文