链式存储结构直接插入python
时间: 2024-03-07 14:45:48 浏览: 28
链式存储结构是一种常见的数据结构,它通过节点之间的指针链接来存储数据。在链式存储结构中,每个节点包含两部分:数据和指向下一个节点的指针。
直接插入是一种链表操作,它将新节点插入到链表的任意位置。具体步骤如下:
1. 创建一个新节点,并将要插入的数据存储在该节点中。
2. 找到插入位置的前一个节点,可以从链表的头节点开始遍历,直到找到合适的位置。
3. 将新节点的指针指向前一个节点的下一个节点。
4. 将前一个节点的指针指向新节点。
以下是一个使用Python实现链式存储结构直接插入的示例代码:
```python
class Node:
def __init__(self, data):
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
def display(self):
current = self.head
while current is not None:
print(current.data, end=" ")
current = current.next
print()
# 示例用法
linked_list = LinkedList()
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
linked_list.display()
```