Python中的链表是一种基本的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。链表在Python中可以通过以下方式实现:
节点类定义
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
链表类定义
class LinkedList:
def __init__(self):
self.head = None
链表操作
添加元素:
def add(self, item):
temp = Node(item)
temp.next = self.head
self.head = temp
遍历链表:
def printList(self):
current = self.head
while current:
print(current.data)
current = current.next
查找元素:
def find(self, data):
curr_node = self.head
while curr_node is not None:
if curr_node.data == data:
return curr_node
curr_node = curr_node.next
return None
删除元素:
def delete(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
prev_node = self.head
curr_node = self.head.next
while curr_node is not None:
if curr_node.data == data:
prev_node.next = curr_node.next
return
prev_node = curr_node
curr_node = curr_node.next
链表在Python中的实际应用包括:
实现队列或堆栈(FIFO/LIFO)。
用于数据结构如图。
在操作系统应用程序的生命周期管理中。
快速插入和删除操作,尤其适用于不需要随机访问的情况。
链表相对于数组的优势在于其插入和删除操作的时间复杂度为O(1),不需要移动其他元素,但缺点是不能像数组那样通过索引快速访问元素。