运用Python 环境,创建单链表,实现查找、插人和删除元素等操作,代码及运行结果,截图插入下侧:
时间: 2024-12-11 18:28:38 浏览: 8
在Python中,我们可以使用内置的数据结构`list`来模拟链表的行为,因为列表在内存中实际上是通过链接的方式存储数据的。然而,为了更清晰地展示链表的概念和基本操作,我们通常会自定义一个Node类来表示节点,并创建一个LinkedList类来管理节点。
首先,我们需要定义Node类:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
```
然后创建LinkedList类,包括查找、插入和删除元素的方法:
```python
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)
def find(self, key):
current = self.head
while current and current.data != key:
current = current.next
return current is not None
def insert(self, key, position):
new_node = Node(key)
if not self.head:
self.head = new_node
elif position == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(position - 1):
if current.next:
current = current.next
if current.next:
new_node.next = current.next
current.next = new_node
def delete(self, key):
if not self.head:
return
elif self.head.data == key:
self.head = self.head.next
else:
current = self.head
prev = None
while current and current.data != key:
prev = current
current = current.next
if current:
prev.next = current.next
# 示例使用
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
print("初始链表:", ll) # 输出:[1, 2, 3]
found = ll.find(2)
if found:
print("找到元素2:", found.data) # 输出:找到元素2: 2
ll.insert(4, 1)
print("插入元素4到位置1后:", ll) # 输出:[1, 4, 2, 3]
ll.delete(2)
print("删除元素2后的链表:", ll) # 输出:[1, 4, 3]
```
由于文本无法显示图片,你可以在本地环境中运行上述代码并查看输出结果。请注意,这只是一个简单的链表实现,实际应用中可能需要考虑更多的边界情况和错误处理。
阅读全文