简介:介绍单链表的基本操作,包括创建、插入、删除和遍历等。通过Python代码实现这些操作,帮助读者更好地理解单链表的数据结构。
单链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。下面我们将通过Python代码实现单链表的基本操作。
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)
在指定位置插入一个节点的代码如下:
def insert(self, index, data):
new_node = Node(data)
if index == 0:
new_node.next = self.head
self.head = new_node
return
current = self.head
curr_index = 0
while curr_index < index-1 and current.next:
current = current.next
curr_index += 1
new_node.next = current.next
current.next = new_node
def remove(self, data):
if self.head is None:
return None
if self.head.data == data:
self.head = self.head.next
return None
current = self.head
while current.next:
if current.next.data == data:
current.next = current.next.next
return None
current = current.next
删除指定位置的节点的代码如下:
由于在单链表中删除指定位置的节点需要先找到要删除节点的前一个节点,因此需要修改上面的 remove
方法,如下所示:
python
python
def remove_at_position(self, index):
if index < 0 or index >= self.length():
return None
if index == 0:
self.head = self.head.next
return None
current = self.head
curr_index = 0
while curr_index < index-1 and current.next:
current = current.next
curr_index += 1
if current.next: # 检查当前节点是否有下一个节点,如果有,则执行删除操作,否则抛出异常。 修改为: if curr_index < index-1 and current.next: # 检查当前节点是否有下一个节点,如果有,则执行删除操作,否则抛出异常。 python
python