用Python写一个程序 进行单链表的插入
时间: 2024-05-03 07:22:36 浏览: 11
以下是一个Python程序,用于单链表的插入操作:
```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, end=' ')
current_node = current_node.next
def insert_at_index(self, data, index):
new_node = Node(data)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
current_node = self.head
for i in range(index-1):
current_node = current_node.next
if current_node is None:
raise Exception("Index out of range")
new_node.next = current_node.next
current_node.next = new_node
# Example usage:
linked_list = LinkedList()
# Inserting elements into the linked list
linked_list.insert(1)
linked_list.insert(2)
linked_list.insert(3)
# Displaying the linked list
linked_list.display() # Output: 1 2 3
# Inserting an element at a specific index
linked_list.insert_at_index(4, 1)
# Displaying the linked list again
linked_list.display() # Output: 1 4 2 3
```
在这个程序中,我们定义了两个类:`Node`和`LinkedList`。`Node`类表示单链表中的节点,具有一个`data`属性和一个`next`属性,指向下一个节点。`LinkedList`类表示单链表本身,具有一个`head`属性,指向第一个节点。
我们定义了三个方法:`insert`、`display`和`insert_at_index`。`insert`方法用于将元素插入到单链表的末尾;`display`方法用于遍历并打印单链表中的所有元素;`insert_at_index`方法用于在特定位置插入元素。
在`insert_at_index`方法中,我们首先创建一个新节点,并将其插入到指定位置。如果插入位置是0,则将新节点插入到头部,并将其`next`指向当前的头节点。否则,我们遍历单链表,找到插入位置之前的节点,并将新节点插入到该节点的后面。
我们还提供了一个示例用法,其中我们首先将三个元素插入到单链表中,然后在第二个位置插入第四个元素,并打印单链表以验证插入操作是否正确。