数据结构顺序表的基本操作编程
时间: 2023-06-26 15:04:00 浏览: 64
下面是顺序表的基本操作的Python代码实现:
```python
class SeqList:
def __init__(self, maxsize=10):
self.maxsize = maxsize
self.list = [None] * self.maxsize
self.length = 0
# 获取顺序表长度
def __len__(self):
return self.length
# 判断顺序表是否为空
def is_empty(self):
return self.length == 0
# 判断顺序表是否已满
def is_full(self):
return self.length == self.maxsize
# 获取指定下标的元素
def get_elem(self, index):
if index < 0 or index >= self.length:
raise IndexError("Index out of range")
return self.list[index]
# 查找元素并返回下标
def find(self, elem):
for i in range(self.length):
if self.list[i] == elem:
return i
return -1
# 在指定下标处插入元素
def insert(self, index, elem):
if self.is_full():
raise Exception("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.list[i+1] = self.list[i]
self.list[index] = elem
self.length += 1
# 在末尾添加元素
def append(self, elem):
self.insert(self.length, elem)
# 删除指定下标的元素
def delete(self, index):
if self.is_empty():
raise Exception("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.list[i] = self.list[i+1]
self.list[self.length-1] = None
self.length -= 1
# 清空顺序表
def clear(self):
self.list = [None] * self.maxsize
self.length = 0
# 打印顺序表
def __repr__(self):
return str(self.list[:self.length])
```
使用方法:
```python
# 创建一个顺序表
lst = SeqList()
# 在末尾添加元素
lst.append(1)
lst.append(2)
lst.append(3)
print(lst) # [1, 2, 3]
# 获取指定下标的元素
print(lst.get_elem(1)) # 2
# 查找元素并返回下标
print(lst.find(2)) # 1
# 在指定下标处插入元素
lst.insert(1, 4)
print(lst) # [1, 4, 2, 3]
# 删除指定下标的元素
lst.delete(2)
print(lst) # [1, 4, 3]
# 清空顺序表
lst.clear()
print(lst) # []
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)