创建一个单链表,实现其删除,插入,查找等基本操作,使用菜单
时间: 2024-10-12 18:10:23 浏览: 28
创建一个简单的单链表数据结构通常包括节点类(Node)和链表类(LinkedList)。下面是基本操作的简单实现:
1. **节点类 Node**:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
```
2. **链表类 LinkedList**:
```python
class LinkedList:
def __init__(self):
self.head = None
# 插入操作
def insert(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, key):
if not self.head:
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 current.next:
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)
```
在这个实现中,你可以通过实例化`LinkedList`并调用相应的方法来进行删除、插入和查找操作。例如:
```python
my_list = LinkedList()
# 插入元素
my_list.insert(1)
my_list.insert(2)
my_list.insert(3)
# 删除元素
my_list.delete(2)
# 查找元素
print(my_list.search(1)) # 输出: True
print(my_list.search(2)) # 输出: False
# 显示链表
my_list.display() # 输出: [1, 3]
```
阅读全文