链表如何插入数据
时间: 2023-07-25 17:06:07 浏览: 38
链表中插入数据的一般步骤如下:
1. 创建一个新节点,将数据存储在该节点中。
2. 找到要插入节点的位置,即新节点应该插入的位置。
3. 将新节点的指针指向原来该位置的下一个节点。
4. 将原来该位置的节点的指针指向新节点。
下面是一个示例代码,其中假设链表中的每个节点都有一个 `data` 属性和一个 `next` 指针属性,指向下一个节点。
```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 = self.head
while current.next is not None:
current = current.next
current.next = new_node
```
在上面的代码中,`insert()` 方法将新节点插入到链表的末尾。如果链表为空,则将新节点设置为头节点;否则,遍历链表直到最后一个节点,然后将最后一个节点的 `next` 属性指向新节点。