数据结构单向链表插入代码
时间: 2023-05-26 15:04:06 浏览: 45
以下是单向链表的插入操作的示例代码:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = new_node
def display(self):
current_node = self.head
while current_node is not None:
print(current_node.data)
current_node = current_node.next
def insert_at(self, index, data):
new_node = Node(data)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
count = 0
prev_node = None
current_node = self.head
while count < index and current_node is not None:
prev_node = current_node
current_node = current_node.next
count += 1
prev_node.next = new_node
new_node.next = current_node
```
在这个示例中,我们定义了一个`Node`类来存储链表的每个节点,`LinkedList`类则用于维护链表本身。`insert`方法用于在链表末尾插入一个值,`insert_at`方法可以在指定位置插入一个值。`display`方法用于打印链表中所有的值。此外,我们还实现了链表的头指针(`head`)方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)