实现编程单向链表建立、删除、插入、输出
时间: 2023-10-10 20:13:24 浏览: 58
好的,下面是一个简单的单向链表的实现,包括建立、删除、插入、输出操作:
```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 delete_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 insert_node(self, data, new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
if self.head.data == data:
new_node.next = self.head
self.head = new_node
return
current = self.head
while current.next is not None:
if current.next.data == data:
new_node.next = current.next
current.next = new_node
return
current = current.next
def print_list(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
```
下面是使用这个类的一个示例:
```python
linked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.print_list() # 输出 1 2 3
linked_list.delete_node(2)
linked_list.print_list() # 输出 1 3
linked_list.insert_node(1, 4)
linked_list.print_list() # 输出 4 1 3
```
这个单向链表实现比较简单,仅供参考。实际上,单向链表还可以实现很多其他的操作,如查找、排序等。
相关推荐
![](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)