链表是一种重要的数据结构,需要动态的进行存储分配,要求通过函数分别实现动态链表的建立、结点的插入、结点的删除以及链表的输出。
时间: 2024-02-21 20:59:59 浏览: 31
好的,我可以帮你实现这些功能。以下是动态链表的建立、结点的插入、结点的删除和链表的输出的函数实现:
```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 insert_node(self, data, position):
new_node = Node(data)
if position < 1:
print("Invalid position")
return
elif position == 1:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for i in range(1, position - 1):
if current is None:
break
current = current.next
if current is None:
print("Invalid position")
else:
new_node.next = current.next
current.next = new_node
def delete_node(self, key):
current = self.head
if current is not None and current.data == key:
self.head = current.next
current = None
return
prev = None
while current is not None and current.data != key:
prev = current
current = current.next
if current is None:
print("Key not found")
else:
prev.next = current.next
current = None
def print_list(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
```
其中,`Node`类表示链表中的节点,包括数据和指向下一个节点的指针;`LinkedList`类表示整个链表,包括头节点和各种操作。`add_node`函数实现链表的建立,`insert_node`函数实现节点的插入,`delete_node`函数实现节点的删除,`print_list`函数实现链表的输出。你可以根据具体需求调用这些函数来操作链表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)