请编程实现一个对顺序表进行基本操作的系统,主要包括表的创建、输入、查询、取值、插入、删除和输出等操作
时间: 2024-10-18 18:16:45 浏览: 30
用C++实现简单的顺序表
在Python中,我们可以创建一个简单的顺序表(也称为数组)数据结构,并实现一些基本的操作。这里是一个基础版本的实现:
```python
class LinkedList:
def __init__(self):
self.head = None
# 创建列表
def create(self):
self.head = Node(None)
# 输入元素
def insert(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 查询元素是否存在
def search(self, value):
current = self.head
while current and current.value != value:
current = current.next
return current is not None
# 取值并返回指定位置的元素
def get_value(self, index):
if index < 0 or index >= self.size():
raise IndexError("Index out of range")
current = self.head
for _ in range(index):
current = current.next
return current.value
# 插入元素到指定位置
def insert_at(self, index, value):
if index < 0 or index > self.size():
raise IndexError("Invalid index")
new_node = Node(value)
if not self.head:
self.head = new_node
elif index == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
# 删除指定位置的元素
def delete(self, index):
if index < 0 or index >= self.size():
raise IndexError("Invalid index")
if not self.head:
return
if index == 0:
self.head = self.head.next
else:
current = self.head
for _ in range(index - 1):
current = current.next
current.next = current.next.next
# 输出整个列表
def print_list(self):
elements = []
current = self.head
while current:
elements.append(current.value)
current = current.next
print(elements)
# 返回列表长度
def size(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
# 定义节点
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
```
你可以使用这个`LinkedList`类来实现基本的顺序表操作。例如:
```python
list = LinkedList()
list.create()
list.insert(5)
list.insert(3)
list.insert(8)
list.print_list() # 输出 [5, 3, 8]
print(list.search(8)) # 输出 True
print(list.get_value(1)) # 输出 3
list.insert_at(1, 7) # 插入 7 在索引 1
list.delete(0) # 删除第一个元素
list.print_list() # 输出 [3, 7, 8]
```
阅读全文