写一个单链表的代码,包含插入,删除,查询
时间: 2024-05-03 14:22:53 浏览: 50
单链表插入和删除
5星 · 资源好评率100%
单链表是一种链式数据结构,每个节点包含一个数据元素和一个指向下一个节点的指针。
以下是一个基本的单链表代码实现,包含了插入、删除和查询操作:
```python
# 定义一个节点类
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 定义一个单链表类
class LinkedList:
def __init__(self):
self.head = None
# 插入操作
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
curr_node = self.head
while curr_node.next is not None:
curr_node = curr_node.next
curr_node.next = new_node
# 删除操作
def delete(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
else:
curr_node = self.head
while curr_node.next is not None:
if curr_node.next.data == data:
curr_node.next = curr_node.next.next
return
curr_node = curr_node.next
# 查询操作
def search(self, data):
curr_node = self.head
while curr_node is not None:
if curr_node.data == data:
return True
curr_node = curr_node.next
return False
```
使用示例:
```python
ll = LinkedList()
ll.insert(1)
ll.insert(2)
ll.insert(3)
print(ll.search(2)) # True
ll.delete(2)
print(ll.search(2)) # False
```
阅读全文