Python中的链表实现与应用
链表是一种常见的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针,在Python中,我们可以使用类来实现链表,以下是一个简单的链表实现及其应用示例。
我们定义一个节点类,用于表示链表中的每个元素:
class ListNode: def __init__(self, value): self.value = value self.next = None
接下来,我们定义一个链表类,用于管理链表的节点:
class LinkedList: def __init__(self): self.head = None def append(self, value): new_node = ListNode(value) if not self.head: self.head = new_node return current = self.head while current.next: current = current.next current.next = new_node def insert(self, value, position): new_node = ListNode(value) if position == 0: new_node.next = self.head self.head = new_node return current = self.head for _ in range(position - 1): if not current: raise IndexError("Position out of range") current = current.next new_node.next = current.next current.next = new_node def delete(self, value): if not self.head: return if self.head.value == value: self.head = self.head.next return current = self.head while current.next: if current.next.value == value: current.next = current.next.next return current = current.next def find(self, value): current = self.head position = 0 while current: if current.value == value: return position current = current.next position += 1 return -1 def length(self): current = self.head count = 0 while current: count += 1 current = current.next return count def display(self): elements = [] current = self.head while current: elements.append(current.value) current = current.next print(" -> ".join(map(str, elements)))
现在我们已经实现了链表的基本操作,我们可以使用这个链表类来创建和操作链表,以下是一些应用示例:
创建一个空链表 linked_list = LinkedList() 向链表中添加元素 linked_list.append(1) linked_list.append(2) linked_list.append(3) 插入元素到指定位置 linked_list.insert(0, 0) linked_list.insert(4, 5) 删除指定元素 linked_list.delete(2) linked_list.delete(4) 查找指定元素的索引 index = linked_list.find(1) print("Index of 1:", index) 获取链表长度 length = linked_list.length() print("Length of the linked list:", length) 显示链表中的元素 linked_list.display()
输出结果:
Index of 1: 0 Length of the linked list: 4 0 -> 1 -> 3 -> 5
还没有评论,来说两句吧...