链表
链表(Linked List)
链表是一种常见的数据结构,它由一系列节点(Node)组成,每个节点包含数据和指向下一个节点的引用(指针)。链表的主要优点是插入和删除操作的时间复杂度为O(1),但访问特定元素的时间复杂度为O(n)。
单链表(Singly Linked List)
单链表是最简单的链表形式,每个节点只有一个指向下一个节点的引用。
节点类(Node Class)
首先,我们需要定义一个节点类,每个节点包含数据和指向下一个节点的引用。
class Node:
def __init__(self, data):
self.data = data
self.next = None
链表类(Linked List Class)
接下来,我们定义一个链表类,包含链表的头节点和一些基本操作。
class LinkedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head is None
def append(self, data):
new_node = Node(data)
if self.is_empty():
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def delete(self, key):
current = self.head
previous = None
while current and current.data != key:
previous = current
current = current.next
if current is None:
return
if previous is None:
self.head = current.next
else:
previous.next = current.next
def search(self, key):
current = self.head
while current and current.data != key:
current = current.next
return current is not None
def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current