本关任务:编写程序实现节点类 Node,实现链表的基本操作。
时间: 2023-09-29 21:08:36 浏览: 68
好的,以下是实现节点类 Node 和链表的基本操作的 Python 代码:
```python
class Node:
"""
链表节点的类
"""
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
class LinkedList:
"""
链表类
"""
def __init__(self):
self.head = None
def is_empty(self):
"""
判断链表是否为空
"""
return self.head is None
def add(self, data):
"""
在链表头部添加一个元素
"""
new_node = Node(data)
new_node.next_node = self.head
self.head = new_node
def append(self, data):
"""
在链表尾部添加一个元素
"""
new_node = Node(data)
if self.is_empty():
self.head = new_node
else:
current_node = self.head
while current_node.next_node is not None:
current_node = current_node.next_node
current_node.next_node = new_node
def search(self, data):
"""
查找链表中是否存在某个元素
"""
current_node = self.head
while current_node is not None:
if current_node.data == data:
return True
current_node = current_node.next_node
return False
def remove(self, data):
"""
删除链表中某个元素
"""
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next_node
return
current_node = self.head
while current_node.next_node is not None:
if current_node.next_node.data == data:
current_node.next_node = current_node.next_node.next_node
return
current_node = current_node.next_node
def print_list(self):
"""
打印链表中的所有元素
"""
current_node = self.head
while current_node is not None:
print(current_node.data, end=" -> ")
current_node = current_node.next_node
print("None")
```
以上代码实现了链表的基本操作,包括判断链表是否为空、在链表头部添加元素、在链表尾部添加元素、查找元素是否在链表中、删除元素、打印链表中所有元素等操作。可以通过以下方式使用链表:
```python
# 创建一个链表
linked_list = LinkedList()
# 在链表头部添加元素
linked_list.add(3)
linked_list.add(2)
linked_list.add(1)
# 在链表尾部添加元素
linked_list.append(4)
linked_list.append(5)
# 查找元素是否在链表中
print(linked_list.search(3)) # 输出 True
# 删除元素
linked_list.remove(3)
# 打印链表中所有元素
linked_list.print_list() # 输出 1 -> 2 -> 4 -> 5 -> None
```
相关推荐
![vcxproj](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)