定义一个非递减有序、最大长度为 10000 的顺序表,初始表为 空;
时间: 2024-05-09 12:19:56 浏览: 19
以下是 Python 代码实现:
```python
MAX_SIZE = 10000
class OrderedList:
def __init__(self):
self.data = [0] * MAX_SIZE
self.length = 0
def is_empty(self):
return self.length == 0
def is_full(self):
return self.length == MAX_SIZE
def clear(self):
self.length = 0
def append(self, value):
if self.is_full():
raise Exception("The list is full")
if self.is_empty() or value >= self.data[self.length - 1]:
self.data[self.length] = value
self.length += 1
else:
i = self.length - 1
while i >= 0 and value < self.data[i]:
self.data[i + 1] = self.data[i]
i -= 1
self.data[i + 1] = value
self.length += 1
def find(self, value):
for i in range(self.length):
if self.data[i] == value:
return i
elif self.data[i] > value:
break
return -1
def delete(self, value):
if self.is_empty():
raise Exception("The list is empty")
index = self.find(value)
if index == -1:
raise Exception("The value is not in the list")
for i in range(index, self.length - 1):
self.data[i] = self.data[i + 1]
self.length -= 1
```
其中,MAX_SIZE 是表的最大长度,OrderedList 类封装了顺序表的基本操作,包括:
- is_empty:判断表是否为空
- is_full:判断表是否已满
- clear:清空表
- append:在表尾添加元素
- find:查找指定元素的位置
- delete:删除指定元素
在 append 操作中,如果表为空或者新元素大于等于表中最后一个元素,直接在表尾添加新元素;否则,从表尾向前遍历,找到第一个小于等于新元素的位置,插入新元素。这样可以保证表是非递减有序的。
在 delete 操作中,如果表为空或者指定元素不在表中,抛出异常;否则,从指定位置开始,将后面的元素依次向前移动一个位置。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)