python中关于链表的操作
时间: 2023-05-14 15:04:56 浏览: 111
python数据结构之链表详解
Python中可以使用类来实现链表,具体操作包括创建链表、添加节点、删除节点、查找节点等。以下是一个简单的链表类示例:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next is not None:
current = current.next
current.next = new_node
def remove_node(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
current = self.head
while current.next is not None:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
def find_node(self, data):
current = self.head
while current is not None:
if current.data == data:
return True
current = current.next
return False
```
使用示例:
```python
# 创建链表
llist = LinkedList()
# 添加节点
llist.add_node(1)
llist.add_node(2)
llist.add_node(3)
# 删除节点
llist.remove_node(2)
# 查找节点
print(llist.find_node(1)) # True
print(llist.find_node(2)) # False
```
阅读全文