帮我建立线性链表并完成初始化、取值、查找、插入和删除操作。
时间: 2024-09-25 09:17:53 浏览: 33
线性链表是一种数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。在Python中,我们可以使用类来创建链表,并实现相应的操作:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 初始化:创建一个新的空链表
def initialize(self):
self.head = None
# 取值:返回指定位置的节点数据
def get_value(self, position):
if not self.head or position < 0:
return None
current = self.head
for _ in range(position):
current = current.next
return current.data if current else None
# 查找:检查链表中是否存在特定的数据
def search(self, value):
current = self.head
while current is not None:
if current.data == value:
return True
current = current.next
return False
# 插入:在给定位置插入新的节点
def insert(self, value, position):
new_node = Node(value)
if not self.head:
self.head = new_node
return
if position == 0:
new_node.next = self.head
self.head = new_node
return
current = self.head
for _ in range(position - 1):
if current.next is None:
break
current = current.next
new_node.next = current.next
current.next = new_node
# 删除:移除指定位置的节点
def delete(self, position):
if not self.head or position < 0:
return
if position == 0:
self.head = self.head.next
return
current = self.head
prev = None
for _ in range(position - 1):
if current.next is None:
break
prev = current
current = current.next
if current is None:
return
prev.next = current.next
# 使用示例
ll = LinkedList()
ll.initialize()
ll.insert(1, 0) # 在开头插入1
print(ll.get_value(0)) # 输出1
阅读全文