建立一个线性表,依次输入数据元素1,2,3,4,5,6,7,8,9,10,删除数据元素5,依次显示当前线性表中的数据元素,实现ListSearch函数,并输出该线性表中依次搜索9和11时得到的索值
时间: 2024-09-27 20:06:41 浏览: 33
建立一个简单的线性表(例如单链表),可以按照顺序存储数据元素并支持添加、删除和查找操作。首先,我们需要创建节点类和链表类:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 添加元素到链表尾部
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除指定元素
def delete(self, value):
if self.head is None or self.head.data == value:
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != value:
current = current.next
if current.next:
current.next = current.next.next
# 显示链表中的所有元素
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print(elements)
# 实现 ListSearch 函数,搜索特定元素并返回索引
def list_search(self, target):
index = 0
current = self.head
while current:
if current.data == target:
return index
current = current.next
index += 1
return -1 # 如果找不到目标,返回 -1
```
现在我们可以使用这个链表类来完成输入、删除和查找的操作:
```python
# 初始化链表
my_list = LinkedList()
# 输入数据元素
for i in range(1, 11):
my_list.append(i)
print("原始链表:", my_list.display())
# 删除元素5
my_list.delete(5)
print("删除5后的链表:", my_list.display())
# 搜索元素9和11的索引
search_result_9 = my_list.list_search(9)
search_result_11 = my_list.list_search(11)
if search_result_9 != -1:
print(f"元素9的索引是: {search_result_9}")
else:
print("未找到元素9")
if search_result_11 != -1:
print(f"元素11的索引是: {search_result_11}")
else:
print("未找到元素11")
```
阅读全文