单链表的基本操作

作者:暴富20212024.02.19 02:54浏览量:2

简介:介绍单链表的基本操作,包括创建、插入、删除和遍历等。通过Python代码实现这些操作,帮助读者更好地理解单链表的数据结构。

单链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。下面我们将通过Python代码实现单链表的基本操作。

  1. 创建单链表
    创建一个空单链表的代码如下:
  1. class Node:
  2. def __init__(self, data=None):
  3. self.data = data
  4. self.next = None
  5. class LinkedList:
  6. def __init__(self):
  7. self.head = None
  1. 插入节点
    在单链表的末尾插入一个节点的代码如下:
  1. def append(self, data):
  2. if not self.head:
  3. self.head = Node(data)
  4. else:
  5. current = self.head
  6. while current.next:
  7. current = current.next
  8. current.next = Node(data)

在指定位置插入一个节点的代码如下:

  1. def insert(self, index, data):
  2. new_node = Node(data)
  3. if index == 0:
  4. new_node.next = self.head
  5. self.head = new_node
  6. return
  7. current = self.head
  8. curr_index = 0
  9. while curr_index < index-1 and current.next:
  10. current = current.next
  11. curr_index += 1
  12. new_node.next = current.next
  13. current.next = new_node
  1. 删除节点
    删除指定值的节点的代码如下:
  1. def remove(self, data):
  2. if self.head is None:
  3. return None
  4. if self.head.data == data:
  5. self.head = self.head.next
  6. return None
  7. current = self.head
  8. while current.next:
  9. if current.next.data == data:
  10. current.next = current.next.next
  11. return None
  12. current = current.next

删除指定位置的节点的代码如下:

由于在单链表中删除指定位置的节点需要先找到要删除节点的前一个节点,因此需要修改上面的 remove 方法,如下所示:

pythonpython
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: # 检查当前节点是否有下一个节点,如果有,则执行删除操作,否则抛出异常。 pythonpython