将线性表的基本操作用代码实现】
时间: 2024-02-05 22:13:46 浏览: 74
好的,下面是线性表的基本操作的代码实现,以顺序表为例:
```python
class SeqList:
def __init__(self, maxsize=None):
self.maxsize = maxsize
self._item = [None] * self.maxsize
self.length = 0
def __getitem__(self, index):
if isinstance(index, int):
if index < 0 or index >= self.length:
raise IndexError("Index out of range")
return self._item[index]
elif isinstance(index, slice):
start, stop, step = index.indices(self.length)
rng = range(start, stop, step)
return [self._item[i] for i in rng]
else:
raise TypeError("Invalid argument type")
def __setitem__(self, index, value):
if isinstance(index, int):
if index < 0 or index >= self.length:
raise IndexError("Index out of range")
self._item[index] = value
elif isinstance(index, slice):
start, stop, step = index.indices(self.length)
if (stop-start) != len(value):
raise ValueError("Length of slice and value not match")
for i, v in zip(range(start, stop, step), value):
self._item[i] = v
else:
raise TypeError("Invalid argument type")
def __len__(self):
return self.length
def __repr__(self):
return "SeqList(" + repr(self._item[:self.length]) + ")"
def __str__(self):
return "[" + ", ".join(map(str, self._item[:self.length])) + "]"
def insert(self, index, value):
if self.length >= self.maxsize:
raise OverflowError("List is full")
if index < 0 or index > self.length:
raise IndexError("Index out of range")
for i in range(self.length-1, index-1, -1):
self._item[i+1] = self._item[i]
self._item[index] = value
self.length += 1
def delete(self, index):
if self.length == 0:
raise ValueError("List is empty")
if index < 0 or index >= self.length:
raise IndexError("Index out of range")
for i in range(index, self.length-1):
self._item[i] = self._item[i+1]
self._item[self.length-1] = None
self.length -= 1
```
上述代码实现了线性表的基本操作,包括:
- 构造函数:初始化一个空的顺序表
- `__getitem__`:获取指定索引位置的元素,支持切片操作
- `__setitem__`:设置指定索引位置的元素,支持切片操作
- `__len__`:返回顺序表的长度
- `__repr__`:返回顺序表的表示形式,用于调试
- `__str__`:返回顺序表的字符串表示形式,用于打印
- `insert`:在指定索引位置插入一个元素
- `delete`:删除指定索引位置的元素
这些基本操作可以满足大多数线性表的需求。
阅读全文