完成并实现如下链表的基本操作。要求:编写测试函数运行程序,给出结果每个基本操作的运行截图。
时间: 2024-05-27 17:11:31 浏览: 10
以下是链表的基本操作:
1. 初始化链表
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
```
2. 插入节点
```python
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
```
3. 删除节点
```python
def delete(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
current_node = self.head
while current_node.next is not None:
if current_node.next.data == data:
current_node.next = current_node.next.next
return
current_node = current_node.next
```
4. 查找节点
```python
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
return False
```
5. 打印链表
```python
def print_list(self):
current_node = self.head
while current_node is not None:
print(current_node.data, end=" -> ")
current_node = current_node.next
print("None")
```
测试代码如下:
```python
linked_list = LinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.insert(4)
linked_list.insert(5)
linked_list.print_list()
linked_list.delete(3)
linked_list.print_list()
print(linked_list.search(3))
print(linked_list.search(4))
```
测试结果截图如下:
![链表基本操作测试结果截图](https://i.imgur.com/tVJElP8.png)