用Python体现单链表的增删改查
时间: 2024-10-15 21:24:29 浏览: 21
python链接oracle数据库以及数据库的增删改查实例
在Python中,我们可以使用类(Class)来实现单链表的数据结构。单链表包含节点(Node),每个节点通常包含两个部分:数据(data)和指向下一个节点的引用(next)。这里是一个简单的单链表类的实现,包括增删改查操作:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 插入元素到链表头部
def insert_at_start(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# 在特定位置插入元素
def insert_at_position(self, position, data):
if position <= 0:
print("Invalid position")
return
if position == 1:
self.insert_at_start(data)
else:
current = self.head
for _ in range(position - 2):
if not current:
break
current = current.next
if not current:
print("Position out of bounds")
return
new_node = Node(data)
new_node.next = current.next
current.next = new_node
# 删除节点
def delete(self, key):
if not self.head:
print("List is empty")
return
if self.head.data == key:
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != key:
current = current.next
if not current.next:
print(f"{key} not found in the list")
else:
current.next = current.next.next
# 查询节点是否存在
def search(self, key):
current = self.head
while current:
if current.data == key:
return True
current = current.next
return False
# 打印链表
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("Elements in the linked list:", elements)
# 示例
linked_list = LinkedList()
linked_list.insert_at_start(5)
linked_list.insert_at_position(2, 7)
linked_list.display() # 输出: Elements in the linked list: [5, 7]
print(linked_list.search(7)) # 输出: True
linked_list.delete(7)
linked_list.display()
阅读全文